Home > Back-end >  How do you access a common property of generic type inside a method in C# (using constraints?)
How do you access a common property of generic type inside a method in C# (using constraints?)

Time:02-24

I have the same method that repeats in my project for different classes:

public Task DoSomething(Class1 class)
{
    // do stuff
    var commonProperty = class.commonProperty 
    // do stuff
}

And in a different service

public Task DoSomething(Class2 class)
{
    // do stuff
    var commonProperty = class.commonProperty 
    // do stuff
}

I have learnt that I can use generic types and believe this would be a good place to apply this - something like :

public Task DoSomething<T>(T class) 
{
    // do stuff
    var commonProperty = class.commonProperty 
    // do stuff
}

But I can't access the property as such and can't find how to add multiple options for constraints.

CodePudding user response:

First you must create a hierarchy of objects:

public class BaseClass
{
    public object CommonProperty { get; set; }
}

public class Class1 : BaseClass
{
}

public class Class2 : BaseClass
{
}

Then you can use the where generic type constraint to specify the generic type:

public Task DoSomething<T>(T class) where T : BaseClass
{
    // do stuff
    var commonProperty = class.commonProperty 
    // do stuff
}
  • Related