6

I have this structure.

public class FirstClass
{
   public List<Foo> FooList{ get; set; }
}

public class Foo{
   //Ex:
   //public string Name{ get; set; }  
}

public List<Foo> GetFoo(){
//I'm use Firstclass like this here typeof(FirstClass);
//I want create here dynamic property for Foo class.
}

And my problem is, i want create property for "Foo" class from "GetFoo()" function. Same time, this function return "List" "Foo" type. I'm research "Dynamically Add C# Properties at Runtime", "How to dynamically create a class in C#?" but the answers in these links are not referenced as return values or referenced to another class. How i can do this?

2
  • 6
    If you describe why you need that, someone might suggest a better way to solve the problem instead of adding properties at runtime. Commented Dec 12, 2017 at 8:15
  • @Evk I think it is not really necessary to think about the problem again and thank you. Commented Dec 12, 2017 at 8:48

2 Answers 2

2

You can dynamically create classes, which inherits Foo, with any additional properties. Thus you can add instances of those dynamic classes into List<Foo>.

To do so, one can generate a code string like following:

var bar1Code = @"
public class Bar1 : Foo
{
    public Bar1(int value)
    {
        NewProperty = value;
    }
    public int NewProperty {get; set; }
}
";

Then compile it using CSharpCodeProvider:

var compilerResults = new CSharpCodeProvider()
    .CompileAssemblyFromSource(
        new CompilerParameters
        {
            GenerateInMemory = true,
            ReferencedAssemblies =
            {
                "System.dll",
                Assembly.GetExecutingAssembly().Location
            }
        },
        bar1Code);

Then one can create an instance of Bar1, add it to List<Foo> and, e.g. cast it to dynamic to access the dynamic property:

var bar1Type = compilerResults.CompiledAssembly.GetType("Bar1");
var bar2Type = compilerResults.CompiledAssembly.GetType("Bar2"); // By analogy

var firstClass = new FirstClass
{
    FooList = new List<Foo>
    {
        (Foo)Activator.CreateInstance(bar1Type, 56),
        (Foo)Activator.CreateInstance(bar2Type, ...)
    }
};

var dynamicFoo = (dynamic)firstClass.FooList[0];
int i = dynamicFoo.NewProperty; // should be 56
Sign up to request clarification or add additional context in comments.

6 Comments

How can I use such a class at runtime? For ex if I have a library that needs access to this class won't it give compilation error?
@kuldeep it is possible to use this class from a library. For example Castle.DynamicProxy and widely used Moq package use similar pattern to automatically implement interfaces in runtime.
is there a tutorial or sample on this? I am struggling to find anything on Google. I could create a class on the fly that has my models but I am not sure now how to use these model classes
@kuldeep it depends on your purposes. In general it's a good idea to inherit "on-the-fly" classes from some interfaces, known in the compile time. Then one would be able to cast them to that interfaces in the code and thus use their functionality. For example, aforementioned Moq package has class Mock<T> which is capable to implement virtual methods of T on the fly. It also has an Object property with type T which represents the implementation with overridden members of T.
use case is that I want to use a custom serialization libary, because it includes lot of boilerpate code that takes care of things such as Bigendian, numberformatting etc. Now so far this process of generating the classes is at compile time, and we want to have ability to do it dynamically via json file. Two choices are there, either use dynamic parsing via dynamic object OR use code generation (based on json structure) to dump model classes and use existing serializer library for that, clearly in the prior case we can not use this custom serializer library, hence the question.
|
0

Why don't you just use a Dictionary;

public class Foo
{
    public Dictionary<string, object> Properties;

    public Foo()
    {
        Properties = new Dictionary<string, object>();
    }
}
public List<Foo> GetFoo()
{
    var item = new Foo();
    item.Properties.Add("Name","Sample");
    item.Properties.Add("OtherName", "Sample");
    return new List<Foo>{ item };
}

Adding property for a class in runtime, it is not possible to perform.

2 Comments

I'm using Firstclass like this typeof(FirstClass) on GetFoo function. So in FirstClass, FooList variable List<Foo> seems default Foo class type. @Rainman
It could be better to look at this article. You want to deserialize xml by dynamic. stackoverflow.com/questions/13704752/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.