3
public class A
{
   public int Val {get; set;}
   public int B {get; set;}
   public T C{get; set;} // make generic property
}

How can I create generic property in model class using asp.net core. In above code I want to make

"C" property as a generic property and convert that property into particular class.

In "C" will be dynamic property.

Example

public Class D
{
  public int Value1 {get; set;}
}

public Class E
{
  public int Value2 {get; set;}
}

The "C" property have either D or E

Unknow
  • 51
  • 3
  • 1
    You need to declare the class as `public class A` – Chetan Jun 09 '21 at 05:05
  • public object C {get; set;} ? – FatTiger Jun 09 '21 at 05:13
  • In an instance of A, attributes cannot have two types at the same time, either create two instances of A, or the two types have an inheritance relationship – FatTiger Jun 09 '21 at 05:16
  • Generics allow your implementation to be oblivious to the type of the property, but you must still define the exact type when you use it. eg `List`. – Jeremy Lakeman Jun 09 '21 at 05:19
  • Does this answer your question? [Making a generic property](https://stackoverflow.com/questions/271347/making-a-generic-property) – Chetan Jun 09 '21 at 05:31
  • Properties can not be generic, only classes, interfaces, methods, deletgates can be generic. – Chetan Jun 09 '21 at 05:33

1 Answers1

0
public class A<T>
{
   public int A {get; set;}
   public int B {get; set;}
   public T C {get; set;} 
}

And use it like this:

var a = new A<D>() 

OR

var a = new A<E>()

Generic classes and methods

FatTiger
  • 647
  • 5
  • 14
  • I means to say that "C" property will be dynamic property where We can add any types of class. – Unknow Jun 09 '21 at 05:09
  • Maybe you should explain how you want to use it – FatTiger Jun 09 '21 at 05:11
  • @Unknow,the answer of `FatTiger` is correct.You can try to use `var aD = new A { C = new D() };var aE = new A { C = new E() };`,so that C can be type D or E. – Yiyi You Jun 10 '21 at 07:44