Reputation: 5089
Is there a way to hide/show a method if a certain constructor is used? i.e.:
public class SomeClass
{
public SomeClass(string methodA)
{
}
public SomeClass(int methodB)
{
}
public string MethodA()
{
return "";
}
public int MethodB()
{
return 0;
}
}
if SomeClass(string methodA)
is used, then only MethodA()
is available when I instance a new SomeClass
object? The same when SomeClass(int methodB)
is used, then MethodB()
would be available?
Thank you all!
Upvotes: 2
Views: 283
Reputation: 12768
You may be better off using generics for your class. It's a bit less fluid than you're probably looking for (because you have to define the type in the class declaration), but accomplishes what you mainly want, I think.
public class SomeClass<T>
{
public SomeClass(T value)
{
}
public T Method() { return default(T); }
}
Which means that creating an instance of the class would use "new SomeClass(0);" rather than simply "new SomeClass(0);"
Upvotes: 0
Reputation: 203827
No, it's not possible.
What's more likely is that you want to use generics:
public interface IFoo<T>
{
T Method();
}
public class IntFoo : IFoo<int>
{
int value;
public IntFoo(int value)
{
this.value = value;
}
public int Method()
{
return value;
}
}
public class StringFoo : IFoo<string>
{
string value;
public StringFoo(string value)
{
this.value = value;
}
public string Method()
{
return value;
}
}
If you don't need to restrict it to just strings or ints (or don't want to) then something like this might work, or even be better:
public class Foo<T>
{
private T value;
public Foo(T value)
{
this.value = value;
}
public T Method()
{
return value;
}
}
Upvotes: 5
Reputation: 2283
No. This is not possible. You'd be better off creating an abstract class, and creating two separate classes inheriting from the Abstract Class. Refer to Abstract Design Pattern.
Upvotes: 0