Reputation: 583
Is there a way to limit a class so only 1 property can hold value while rest will have to be null. Or do I have just have to handle it by assigning all others to null when any is set?
Is there any more viable way of approaching this?
Upvotes: 2
Views: 183
Reputation: 5543
The difficulty you're having is that you're trying to use a conjunction (AND
) to express a disjunction (OR
).
When you have a class with a bunch of properties like
class Foo
{
public Something Property1 { get; set; }
public SomethingElse Property2 { get; set; }
public Whatever Property3 { get; set; }
}
You're saying that Foo is:
Something
AND SomethingElse
AND Whatever
.
But, what you really want to say is that Foo is:
Something
OR SomethingElse
OR Whatever
.
As David Arno mentioned in his answer, ML languages like F# have a compact way of expressing this idea using discriminated unions. But, the larger concept is that of a sum type, which is the way to express the notion of disjunction (i.e. the logical OR
) in the type system. C# can also easily express sum types, albeit with a bit more typing than F# (no pun intended).
public class Foo
{
public Bar Property { get; set; }
}
public abstract class Bar
{
public class Something : Bar
{
}
public class SomethingElse : Bar
{
}
public class Whatever: Bar
{
}
}
Now we have what you want: Objects of type Foo
are either a Something
or SomethingElse
or Whatever
, but they can only be one of those things at any given time.
Upvotes: 1
Reputation: 1977
you can implement it like this on a class
public class OneProp
{
private string val1;
public string Value1 { get { return val1; } };
private string val2;
public string Value2 { get { return val2; } };
public void SetValue(string propName, string propValue)
{
// null all values here
val1 = null;
val2 = null;
switch(propName)
{
case "Value1":
val1 = propValue;
break;
case "Value2":
val1 = propValue;
break;
}
}
}
then create an instance of it;
OneProp val = new OneProp();
val.SetValue("name", "value");
You can also do it in the constructor.
Upvotes: 0
Reputation: 43264
There is no way built in to C# to do this. What you are describing is handled via discriminated unions in F#, but C# doesn't have such types. You could write your own union class to offer such behaviour though.
Upvotes: 4