Reputation: 5931
assuming that we have two class:
class A
{
public int Prop1 { get; set; }
public int Prop2 { get; set; }
}
class B
{
public int Prop2 { get; set; }
public int Prop3 { get; set; }
}
what is the best way and how to implement method which would take object of type A or B and check if has Prop2 and return object of type passed as arquemnt, sth like this :
T CheckIfHasProp2<T>(T)
{
}
generic, dynamic , interface or sth differnt ? I would take intferace but I don't wanna lose other properties.
Upvotes: 1
Views: 65
Reputation: 276296
The best way would be to know the type of your objects :)
To signal an object has an ability to do something in C#, you use an interface.
Interfaces signify a "can do" relationship. They represent a contract a piece of code must obey.
If Prop2
for example is the ability to eat , you can create an IEat
interface and have classes that can eat inherit from it. In the below example I call the interface IProp2
- you should give your interfaces meaningful names that describe the actual behavior:
interface IProp2
{
int Prop2 { get; set; }
}
class A : IProp2
{
public int Prop1 { get; set; }
public int Prop2 { get; set; }
}
class B : IProp2
{
public int Prop2 { get; set; }
public int Prop3 { get; set; }
}
// inside main
var a = new A();
// check if it's a member, though usually you don't need this
Console.WriteLine(a is IProp2); // true
(This is unlike other languages like TypeScript where inheritance is not nominal, but that's another story).
Note that while dynamic
would work, it works against the type system and it effectively means throwing all the benefits of a statically type checked language away. With interfaces you get a compile time error if one of the classes does not implement the interface it inherits.
Upvotes: 3