sanchop22
sanchop22

Reputation: 2809

Variable class properties due to specific constructor in C#

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?

Upvotes: 2

Views: 56

Answers (2)

Hossein Narimani Rad
Hossein Narimani Rad

Reputation: 32481

use generics

public class A<T>
{
    private T _value;

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

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

Upvotes: 2

Marc Gravell
Marc Gravell

Reputation: 1062865

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.

Upvotes: 8

Related Questions