2

Suppose class A as:

public class A
{
    private string _str;
    private int _int;

    public A(string str)
    {
        this._str = str;
    }

    public A(int num)
    {
        this._int = num;
    }

    public int Num
    {
        get
        {
            return this._int;
        }
    }

    public string Str
    {
        get
        {
            return this._str;
        }
    }
}

I want to hide Str property when i construct class A as

new A(2)

and want to hide Num property when i construct class A as

new A("car").

What should i do?

1
  • 3
    You should say what your use case is, and then decide on an appropriate design for that use case. What you ask for is not only impossible but also goes against basic OO principles. Commented Jan 24, 2013 at 10:59

2 Answers 2

8

That isn't possible with a single class. An A is an A, and has the same properties - regardless of how it is constructed.

You could have 2 subclasses of abstract A, and a factory method...

public abstract class A
{
    class A_Impl<T> : A
    {
        private T val;
        public A_Impl(T val) { this.val = val; }
        public T Value { get { return val; } }
    }
    public static A Create(int i) { return new A_Impl<int>(i); }
    public static A Create(string str) { return new A_Impl<string>(str); }
}

But : the caller will not know about the value unless they cast it.

Sign up to request clarification or add additional context in comments.

2 Comments

Would you give an example or suggest an article regarding to this issue?
@petre well, I've added some code, but fundamentally you are trying to do something that is contrary to object orientation
2

use generics

public class A<T>
{
    private T _value;

    public A(T value)
    {
        this._value= value;
    }

    public TValue
    {
        get
        {
            return this._value;
        }
    }
}

1 Comment

although this would also enable new A(DateTime.Now)for example, meaning the constructor takes any type.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.