Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to make/design a class which can have different type of members at runtime in C#
    text
    copied!<p>I have a situation where I need a class which need to contain information about something which varies at runtime, for example:</p> <pre><code>class Info&lt;T&gt; { public T Max { get; set; } public T Min { get; set; } public T DefaultValue { get; set; } public T Step { get; set; } // Some other stuff } </code></pre> <p>I have to store many instances of this class in a dictionary but problem is that to use dictionary I have to declare one type e.g.</p> <pre><code>Dictionary&lt;string, Info&lt;int&gt;&gt; dict = new Dictionary&lt;string, Info&lt;int&gt;&gt;(); </code></pre> <p>In this case I can't add another type of info e.g. <code>Info&lt;double&gt;</code>. I want something like , I have removed generic version in below case.</p> <pre><code> {"Price", new Info{Min=100,Max=1000,DefaultValue=200,Step=50}} {"Adv", new Info{Min=10.50,Max=500.50,DefaultValue=20.50,Step=1.5}} {"Answer", new Info{Min=false,Max=false,DefaultValue=false,Step=false}} </code></pre> <p>I can use <code>Dictionary&lt;string, Object&gt; dict = new Dictionary&lt;string, Object&gt;();</code></p> <p>but then when I get the dict item back I don't know what type is that, I need to know the type as well e.g. for <code>Price</code> it's int and for Adv it's double , how will I know it at runtime?</p> <p>Actually I want to create a validator(I am using .Net Compact Framework 3.5/can not use any inbuilt system if it exists) for example If I have a class like below..</p> <pre><code>class Demo { public int Price { get; set; } public float Adv { get; set; } public static bool Validate(Demo d) { List&lt;string&gt; err = new List&lt;string&gt;(); // here I have to get Info about the Price // from dictionary, it can be any storage Info priceInfo = GetPriceInfo("Price"); if (d.Price &lt; priceInfo.Min) { d.Price = priceInfo.Min; err.Add("price is lower than Min Price"); } if (d.Price &gt; priceInfo.Max) { d.Price = priceInfo.Max; err.Add("price is above than Max Price"); } // need to do similar for all kinds of properties in the class } } </code></pre> <p>So idea is to store validation information at one place (in dictionary or somewhere else) and then use that info at validation time, I also would like to know if I can design the above scenario in a better way ?</p> <p>Maybe there is a better way to do this , any guidelines please?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload