Create variable of a generic class from a generic class - c#

I want to create a class that can keep a number between to values. Here for I have created my first two generic classes.
The first called LimitRang and keep two limit rang variables; one for the lower rang and for the top rang. The second called NumberLimitRang and keep the number and the first class LimitRang.
When I try to create the variable mvarRang, how is a LimitRang var, in the constructor of NumberLimitRang I receive the error : 'Cannot implicitly convert type 'VariableTypes.Supplement.LimitRang' to 'T'.
My code for LimitRang:
namespace VariableTypes.Supplement
{
/// <summary>
/// Manage the boundaries for a number.
/// </summary>
/// <typeparam name="T">The numberic type for the limit parameters</typeparam>
public class LimitRang<T> where T : IComparable
{
private T mvarLowestLimitNumber;
private T mvarHighestLimitNumber;
/// <summary>
/// The default constructor (between 0 and 100)
/// </summary>
public LimitRang()
{
if (Functions.IsNumericType(typeof(T)))
{
try
{
mvarLowestLimitNumber = (T)Convert.ChangeType(0, typeof(T));
mvarHighestLimitNumber = (T)Convert.ChangeType(100, typeof(T));
}
catch
{
mvarLowestLimitNumber = default(T);
mvarHighestLimitNumber = default(T);
}
}
}
}
}
My code for NumberLimitRang:
namespace VariableTypes
{
/// <summary>
/// Can contain a number that need to be between or equal to two limit numbers
/// </summary>
public class NumberLimitRang<T> where T : IComparable
{
private Supplement.LimitRang<T> mvarRang;
private T mvarNumber;
/// <summary>
/// The default constructor (between 0 and 100/Number = 0)
/// </summary>
public NumberLimitRang(T mvarRang)
{
mvarRang = new Supplement.LimitRang<T>();
mvarNumber = (T)Convert.ChangeType(0, typeof(T));
}
}
}
Even when I replace the two T's into int, I still receive the error:
- private Supplement.LimitRang<int> mvarRang;
- mvarRang = new Supplement.LimitRang<int>();
Can you tell me what I do wrong?
Thx a lot

Problem is here:
public NumberLimitRang(T mvarRang)
{
mvarRang = new LimitRang<T>();
mvarNumber = (T)Convert.ChangeType(0, typeof(T));
}
You pass mvarRang as an argument and you have field with name mvarRang. But in method NumberLimitRang compiler uses mvarRang as argument, wich is type of T and tryes to replace it's value with new LimitRang<T>();.
So, first of all, rename field or argument. For example:
public class NumberLimitRang<T> where T : IComparable
{
private LimitRang<T> _mvarRang;
private T _mvarNumber;
/// <summary>
/// The default constructor (between 0 and 100/Number = 0)
/// </summary>
public NumberLimitRang(T mvarRang)
{
_mvarRang = new LimitRang<T>();
_mvarNumber = (T)Convert.ChangeType(0, typeof(T));
}
}
It's good practice to name fields with _ in the beginning.
But now, your argument mvarRang is unused. Revise your logic in code.

public NumberLimitRang(T mvarRang)
{
mvarRang = new Supplement.LimitRang<T>();
mvarNumber = (T)Convert.ChangeType(0, typeof(T));
}
The constructor takes a variable mvarRang of type T. This declaration hides the instance member mvarRang of the type LimitRang<T>.
Either change the parameter name, or refer to the instance member explicitly using this:
public NumberLimitRang(T mvarRang)
{
this.mvarRang = new Supplement.LimitRang<T>();
mvarNumber = (T)Convert.ChangeType(0, typeof(T));
}

Related

Cast base class to derive class in .NET Core

I want to create a class to call stored procedures in my SQL Server. I'm using C# with .NET Core 3.1. All stored procedures return the same results but in some cases I have to do more activities and then every function has its own return type base on a base class, in the code below called BaseResponse.
public class BaseResponse
{
public int ErrorCode { get; set; }
public string Message { get; set; }
}
public class InvoiceResponse : BaseResponse
{
public bool IsPaid { get; set; }
}
Then, I have my BaseCall that it is responsible to call a stored procedure and return the BaseResponse.
public async Task<BaseResponse> BaseCall(string procedureName, string[] params)
{
BaseResponse rtn = new BaseResponse();
// call SQL Server stored procedure
return rtn;
}
In another class I want to cast the BaseResponse with the derive class. For that, I thought I can cast the BaseResponse with the derive class but I was wrong.
public async Task<InvoiceResponse> GetInvoice(int id)
{
InvoiceResponse rtn = new InvoiceResponse();
BaseResponse response = BaseCall("myprocedure", null);
rtn = (InvoiceResponse)response;
// do something else
return rtn;
}
I saw other two posts (Convert base class to derived class and this one) and I understood I can't cast in the way I wanted. Then I was my extension from that
/// <summary>
/// Class BaseClassConvert.
/// </summary>
public static class BaseClassConvert
{
/// <summary>
/// Maps to new object.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="sourceobject">The sourceobject.</param>
/// <returns>T.</returns>
/// <remarks>
/// The target object is created on the fly and the target type
/// must have a parameterless constructor (either compiler-generated or explicit)
/// </remarks>
public static T MapToNewObject<T>(this object sourceobject) where T : new()
{
// create an instance of the target class
T targetobject = (T)Activator.CreateInstance(typeof(T));
// map the source properties to the target object
MapToExistingObject(sourceobject, targetobject);
return targetobject;
}
/// <summary>
/// Maps to existing object.
/// </summary>
/// <param name="sourceobject">The sourceobject.</param>
/// <param name="targetobject">The targetobject.</param>
/// <remarks>The target object is created beforehand and passed in</remarks>
public static void MapToExistingObject(this object sourceobject, object targetobject)
{
// get the list of properties available in source class
var sourceproperties = sourceobject.GetType().GetProperties().ToList();
// loop through source object properties
sourceproperties.ForEach(sourceproperty =>
{
var targetProp = targetobject.GetType().GetProperty(sourceproperty.Name);
// check whether that property is present in target class and is writeable
if (targetProp != null && targetProp.CanWrite)
{
// if present get the value and map it
var value = sourceobject.GetType().GetProperty(sourceproperty.Name).GetValue(sourceobject, null);
targetobject.GetType().GetProperty(sourceproperty.Name).SetValue(targetobject, value, null);
}
});
}
}
This code is working and I can use it like:
public async Task<InvoiceResponse> GetInvoice(int id)
{
InvoiceResponse rtn = new InvoiceResponse();
BaseResponse response = BaseCall("myprocedure", null);
response.MapToExistingObject(rtn);
// do something else
return rtn;
}
My questions are:
is there a more efficient way to cast the base class with a derive class in .NET Core?
is this the best practice for casting?
any other guide lines?
this procedure is using Reflection. In performance point of view, is it the right and cheapest way to implement this cast?
You can't cast (without getting error) expression returning/containing base class instance to any inheritor type if this instance not actually inherits it (and to check this there are type-testing operators in C#). Casting as the docs state is an attempt by compiler to perform an explicit conversion in runtime. Also as you mentioned you can't implement custom explicit conversion from or to base class.
What are you looking for (and trying to do) is called mapping and there are a lot of libraries for that, including but not limited to Automapper, Mapster or ExpressMapper for example.

Converting string back to enum

Is there a cleaner, more clever way to do this?
I'm hitting a DB to get data to fill an object and am converting a database string value back into its enum (we can assume that all values in the database are indeed values in the matching enum)
The line in question is the line below that sets EventLog.ActionType...the reason I began to question my method is because after the equals sign, VS2010 keeps trying to override what I'm typing by putting this: "= EventActionType("
using (..<snip>..)
{
while (reader.Read())
{
// <snip>
eventLog.ActionType = (EventActionType)Enum.Parse(typeof(EventActionType), reader[3].ToString());
...etc...
As far as I know, this is the best way to do it. I've set up a utility class to wrap this functionality with methods that make this look cleaner, though.
/// <summary>
/// Convenience method to parse a string as an enum type
/// </summary>
public static T ParseEnum<T>(this string enumValue)
where T : struct, IConvertible
{
return EnumUtil<T>.Parse(enumValue);
}
/// <summary>
/// Utility methods for enum values. This static type will fail to initialize
/// (throwing a <see cref="TypeInitializationException"/>) if
/// you try to provide a value that is not an enum.
/// </summary>
/// <typeparam name="T">An enum type. </typeparam>
public static class EnumUtil<T>
where T : struct, IConvertible // Try to get as much of a static check as we can.
{
// The .NET framework doesn't provide a compile-checked
// way to ensure that a type is an enum, so we have to check when the type
// is statically invoked.
static EnumUtil()
{
// Throw Exception on static initialization if the given type isn't an enum.
Require.That(typeof (T).IsEnum, () => typeof(T).FullName + " is not an enum type.");
}
public static T Parse(string enumValue)
{
var parsedValue = (T)System.Enum.Parse(typeof (T), enumValue);
//Require that the parsed value is defined
Require.That(parsedValue.IsDefined(),
() => new ArgumentException(string.Format("{0} is not a defined value for enum type {1}",
enumValue, typeof(T).FullName)));
return parsedValue;
}
public static bool IsDefined(T enumValue)
{
return System.Enum.IsDefined(typeof (T), enumValue);
}
}
With these utility methods, you can just say:
eventLog.ActionType = reader[3].ToString().ParseEnum<EventActionType>();
You can use extension methods to give some syntactic sugar to your code. You can even made this extension methods generics.
This is the kind of code I'm talking about: http://geekswithblogs.net/sdorman/archive/2007/09/25/Generic-Enum-Parsing-with-Extension-Methods.aspx
public static T EnumParse<T>(this string value)
{
return EnumHelper.EnumParse<T>(value, false);
}
public static T EnumParse<T>(this string value, bool ignoreCase)
{
if (value == null)
{
throw new ArgumentNullException("value");
}
value = value.Trim();
if (value.Length == 0)
{
throw new ArgumentException("Must specify valid information for parsing in the string.", "value");
}
Type t = typeof(T);
if (!t.IsEnum)
{
throw new ArgumentException("Type provided must be an Enum.", "T");
}
T enumType = (T)Enum.Parse(t, value, ignoreCase);
return enumType;
}
SimpleEnum enumVal = Enum.Parse<SimpleEnum>(stringValue);
Could use an extension method like so:
public static EventActionType ToEventActionType(this Blah #this) {
return (EventActionType)Enum.Parse(typeof(EventActionType), #this.ToString());
}
And use it like:
eventLog.ActionType = reader[3].ToEventActionType();
Where Blah above is the type of reader[3].
You could get any enum value back, not just EventActionType as in your case with the followin method.
public static T GetEnumFromName<T>(this object #enum)
{
return (T)Enum.Parse(typeof(T), #enum.ToString());
}
You can call it then,
eventLog.ActionType = reader[3].GetEnumFromName<EventActionType>()
This is a more generic approach.
#StriplingWarrior's answer didn't work at first try, so I made some modifications:
Helpers/EnumParser.cs
namespace MyProject.Helpers
{
/// <summary>
/// Utility methods for enum values. This static type will fail to initialize
/// (throwing a <see cref="TypeInitializationException"/>) if
/// you try to provide a value that is not an enum.
/// </summary>
/// <typeparam name="T">An enum type. </typeparam>
public static class EnumParser<T>
where T : struct, IConvertible // Try to get as much of a static check as we can.
{
// The .NET framework doesn't provide a compile-checked
// way to ensure that a type is an enum, so we have to check when the type
// is statically invoked.
static EnumParser()
{
// Throw Exception on static initialization if the given type isn't an enum.
if (!typeof (T).IsEnum)
throw new Exception(typeof(T).FullName + " is not an enum type.");
}
public static T Parse(string enumValue)
{
var parsedValue = (T)Enum.Parse(typeof (T), enumValue);
//Require that the parsed value is defined
if (!IsDefined(parsedValue))
throw new ArgumentException(string.Format("{0} is not a defined value for enum type {1}",
enumValue, typeof(T).FullName));
return parsedValue;
}
public static bool IsDefined(T enumValue)
{
return Enum.IsDefined(typeof (T), enumValue);
}
}
}
Extensions/ParseEnumExtension.cs
namespace MyProject.Extensions
{
public static class ParseEnumExtension
{
/// <summary>
/// Convenience method to parse a string as an enum type
/// </summary>
public static T ParseEnum<T>(this string enumValue)
where T : struct, IConvertible
{
return EnumParser<T>.Parse(enumValue);
}
}
}

Pass variable type to a method without enumerating

I want to be able to pass a variable type to a method, mainly so that I can pass an entity framework query to a method that will apply common includes of nested object.
This is what I want to do...
public Person GetPersonByID(int personID)
{
var query = from Perspn p in Context.Persons
where p.PersonID = personID
select p;
ObjectQuery<Person> personQuery = ApplyCommonIncludes<Person>(query);
return personQuery.FirstOrDefault();
}
public ObjectQuery<T> ApplyCommonIncludes<T>(SomeType query)
{
return ((ObjectQuery<T>)query)
.Include("Orders")
.Include("LoginHistory");
}
Seems to be you actually want SomeType to be ObjectQuery<T>, right?
public ObjectQuery<T> ApplyCommonIncludes<T>(ObjectQuery<T> query)
{
return query
.Include("Orders")
.Include("LoginHistory");
}
This is valid syntax. Is there any problem with this?
This ought to work and do delayed execution (I think this is what you mean by "without enumerating") until FirstOrDefault() is called.
I ended up creating a different approach. My repository now has a list of string used for Includes. To retain type safety for creating includes, I created the following class:
/// <summary>
/// Builds Includes
/// </summary>
public class IncludeBuilder
{
/// <summary>
/// List of parts for the Include
/// </summary>
private List<string> Parts;
/// <summary>
/// Creates a new IncludeBuilder
/// </summary>
private IncludeBuilder()
{
this.Parts = new List<string>();
}
/// <summary>
/// Creates a new IncludeBuilder
/// </summary>
public static IncludeBuilder Create()
{
return new IncludeBuilder();
}
/// <summary>
/// Adds a property name to the builder
/// </summary>
public IncludeBuilder AddPart<TEntity, TProp>(Expression<Func<TEntity, TProp>> expression)
{
string propName = ExpressionHelper.GetPropertyNameFromExpression(expression);
this.Parts.Add(propName);
return this;
}
/// <summary>
/// Gets a value of the include parts separated by
/// a decimal
/// </summary>
public override string ToString()
{
return string.Join(".", this.Parts.ToArray());
}
This allows me to do this...
myPersonRepository.AppendInclude(
IncludeBuilder.Create()
.AddPart((Person p) => p.Orders)
.AddPart((Order o) => o.Items));
The above statement passes expressions to the IncludeBuilder class which then translates the above into "Orders.Items".
I then created helper methods in my RepositoryBase that given an ObjectQuery, will apply the includes, execute the query, and return the result. Not quite what I was looking for, but works well.

How do I create dynamic properties in C#?

I am looking for a way to create a class with a set of static properties. At run time, I want to be able to add other dynamic properties to this object from the database. I'd also like to add sorting and filtering capabilities to these objects.
How do I do this in C#?
You might use a dictionary, say
Dictionary<string,object> properties;
I think in most cases where something similar is done, it's done like this.
In any case, you would not gain anything from creating a "real" property with set and get accessors, since it would be created only at run-time and you would not be using it in your code...
Here is an example, showing a possible implementation of filtering and sorting (no error checking):
using System;
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApplication1 {
class ObjectWithProperties {
Dictionary<string, object> properties = new Dictionary<string,object>();
public object this[string name] {
get {
if (properties.ContainsKey(name)){
return properties[name];
}
return null;
}
set {
properties[name] = value;
}
}
}
class Comparer<T> : IComparer<ObjectWithProperties> where T : IComparable {
string m_attributeName;
public Comparer(string attributeName){
m_attributeName = attributeName;
}
public int Compare(ObjectWithProperties x, ObjectWithProperties y) {
return ((T)x[m_attributeName]).CompareTo((T)y[m_attributeName]);
}
}
class Program {
static void Main(string[] args) {
// create some objects and fill a list
var obj1 = new ObjectWithProperties();
obj1["test"] = 100;
var obj2 = new ObjectWithProperties();
obj2["test"] = 200;
var obj3 = new ObjectWithProperties();
obj3["test"] = 150;
var objects = new List<ObjectWithProperties>(new ObjectWithProperties[]{ obj1, obj2, obj3 });
// filtering:
Console.WriteLine("Filtering:");
var filtered = from obj in objects
where (int)obj["test"] >= 150
select obj;
foreach (var obj in filtered){
Console.WriteLine(obj["test"]);
}
// sorting:
Console.WriteLine("Sorting:");
Comparer<int> c = new Comparer<int>("test");
objects.Sort(c);
foreach (var obj in objects) {
Console.WriteLine(obj["test"]);
}
}
}
}
If you need this for data-binding purposes, you can do this with a custom descriptor model... by implementing ICustomTypeDescriptor, TypeDescriptionProvider and/or TypeCoverter, you can create your own PropertyDescriptor instances at runtime. This is what controls like DataGridView, PropertyGrid etc use to display properties.
To bind to lists, you'd need ITypedList and IList; for basic sorting: IBindingList; for filtering and advanced sorting: IBindingListView; for full "new row" support (DataGridView): ICancelAddNew (phew!).
It is a lot of work though. DataTable (although I hate it) is cheap way of doing the same thing. If you don't need data-binding, just use a hashtable ;-p
Here's a simple example - but you can do a lot more...
Use ExpandoObject like the ViewBag in MVC 3.
Create a Hashtable called "Properties" and add your properties to it.
I'm not sure you really want to do what you say you want to do, but it's not for me to reason why!
You cannot add properties to a class after it has been JITed.
The closest you could get would be to dynamically create a subtype with Reflection.Emit and copy the existing fields over, but you'd have to update all references to the the object yourself.
You also wouldn't be able to access those properties at compile time.
Something like:
public class Dynamic
{
public Dynamic Add<T>(string key, T value)
{
AssemblyBuilder assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(new AssemblyName("DynamicAssembly"), AssemblyBuilderAccess.Run);
ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("Dynamic.dll");
TypeBuilder typeBuilder = moduleBuilder.DefineType(Guid.NewGuid().ToString());
typeBuilder.SetParent(this.GetType());
PropertyBuilder propertyBuilder = typeBuilder.DefineProperty(key, PropertyAttributes.None, typeof(T), Type.EmptyTypes);
MethodBuilder getMethodBuilder = typeBuilder.DefineMethod("get_" + key, MethodAttributes.Public, CallingConventions.HasThis, typeof(T), Type.EmptyTypes);
ILGenerator getter = getMethodBuilder.GetILGenerator();
getter.Emit(OpCodes.Ldarg_0);
getter.Emit(OpCodes.Ldstr, key);
getter.Emit(OpCodes.Callvirt, typeof(Dynamic).GetMethod("Get", BindingFlags.Instance | BindingFlags.NonPublic).MakeGenericMethod(typeof(T)));
getter.Emit(OpCodes.Ret);
propertyBuilder.SetGetMethod(getMethodBuilder);
Type type = typeBuilder.CreateType();
Dynamic child = (Dynamic)Activator.CreateInstance(type);
child.dictionary = this.dictionary;
dictionary.Add(key, value);
return child;
}
protected T Get<T>(string key)
{
return (T)dictionary[key];
}
private Dictionary<string, object> dictionary = new Dictionary<string,object>();
}
I don't have VS installed on this machine so let me know if there are any massive bugs (well... other than the massive performance problems, but I didn't write the specification!)
Now you can use it:
Dynamic d = new Dynamic();
d = d.Add("MyProperty", 42);
Console.WriteLine(d.GetType().GetProperty("MyProperty").GetValue(d, null));
You could also use it like a normal property in a language that supports late binding (for example, VB.NET)
I have done exactly this with an ICustomTypeDescriptor interface and a Dictionary.
Implementing ICustomTypeDescriptor for dynamic properties:
I have recently had a requirement to bind a grid view to a record object that could have any number of properties that can be added and removed at runtime. This was to allow a user to add a new column to a result set to enter an additional set of data.
This can be achieved by having each data 'row' as a dictionary with the key being the property name and the value being a string or a class that can store the value of the property for the specified row. Of course having a List of Dictionary objects will not be able to be bound to a grid. This is where the ICustomTypeDescriptor comes in.
By creating a wrapper class for the Dictionary and making it adhere to the ICustomTypeDescriptor interface the behaviour for returning properties for an object can be overridden.
Take a look at the implementation of the data 'row' class below:
/// <summary>
/// Class to manage test result row data functions
/// </summary>
public class TestResultRowWrapper : Dictionary<string, TestResultValue>, ICustomTypeDescriptor
{
//- METHODS -----------------------------------------------------------------------------------------------------------------
#region Methods
/// <summary>
/// Gets the Attributes for the object
/// </summary>
AttributeCollection ICustomTypeDescriptor.GetAttributes()
{
return new AttributeCollection(null);
}
/// <summary>
/// Gets the Class name
/// </summary>
string ICustomTypeDescriptor.GetClassName()
{
return null;
}
/// <summary>
/// Gets the component Name
/// </summary>
string ICustomTypeDescriptor.GetComponentName()
{
return null;
}
/// <summary>
/// Gets the Type Converter
/// </summary>
TypeConverter ICustomTypeDescriptor.GetConverter()
{
return null;
}
/// <summary>
/// Gets the Default Event
/// </summary>
/// <returns></returns>
EventDescriptor ICustomTypeDescriptor.GetDefaultEvent()
{
return null;
}
/// <summary>
/// Gets the Default Property
/// </summary>
PropertyDescriptor ICustomTypeDescriptor.GetDefaultProperty()
{
return null;
}
/// <summary>
/// Gets the Editor
/// </summary>
object ICustomTypeDescriptor.GetEditor(Type editorBaseType)
{
return null;
}
/// <summary>
/// Gets the Events
/// </summary>
EventDescriptorCollection ICustomTypeDescriptor.GetEvents(Attribute[] attributes)
{
return new EventDescriptorCollection(null);
}
/// <summary>
/// Gets the events
/// </summary>
EventDescriptorCollection ICustomTypeDescriptor.GetEvents()
{
return new EventDescriptorCollection(null);
}
/// <summary>
/// Gets the properties
/// </summary>
PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties(Attribute[] attributes)
{
List<propertydescriptor> properties = new List<propertydescriptor>();
//Add property descriptors for each entry in the dictionary
foreach (string key in this.Keys)
{
properties.Add(new TestResultPropertyDescriptor(key));
}
//Get properties also belonging to this class also
PropertyDescriptorCollection pdc = TypeDescriptor.GetProperties(this.GetType(), attributes);
foreach (PropertyDescriptor oPropertyDescriptor in pdc)
{
properties.Add(oPropertyDescriptor);
}
return new PropertyDescriptorCollection(properties.ToArray());
}
/// <summary>
/// gets the Properties
/// </summary>
PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties()
{
return ((ICustomTypeDescriptor)this).GetProperties(null);
}
/// <summary>
/// Gets the property owner
/// </summary>
object ICustomTypeDescriptor.GetPropertyOwner(PropertyDescriptor pd)
{
return this;
}
#endregion Methods
//---------------------------------------------------------------------------------------------------------------------------
}
Note: In the GetProperties method I Could Cache the PropertyDescriptors once read for performance but as I'm adding and removing columns at runtime I always want them rebuilt
You will also notice in the GetProperties method that the Property Descriptors added for the dictionary entries are of type TestResultPropertyDescriptor. This is a custom Property Descriptor class that manages how properties are set and retrieved. Take a look at the implementation below:
/// <summary>
/// Property Descriptor for Test Result Row Wrapper
/// </summary>
public class TestResultPropertyDescriptor : PropertyDescriptor
{
//- PROPERTIES --------------------------------------------------------------------------------------------------------------
#region Properties
/// <summary>
/// Component Type
/// </summary>
public override Type ComponentType
{
get { return typeof(Dictionary<string, TestResultValue>); }
}
/// <summary>
/// Gets whether its read only
/// </summary>
public override bool IsReadOnly
{
get { return false; }
}
/// <summary>
/// Gets the Property Type
/// </summary>
public override Type PropertyType
{
get { return typeof(string); }
}
#endregion Properties
//- CONSTRUCTOR -------------------------------------------------------------------------------------------------------------
#region Constructor
/// <summary>
/// Constructor
/// </summary>
public TestResultPropertyDescriptor(string key)
: base(key, null)
{
}
#endregion Constructor
//- METHODS -----------------------------------------------------------------------------------------------------------------
#region Methods
/// <summary>
/// Can Reset Value
/// </summary>
public override bool CanResetValue(object component)
{
return true;
}
/// <summary>
/// Gets the Value
/// </summary>
public override object GetValue(object component)
{
return ((Dictionary<string, TestResultValue>)component)[base.Name].Value;
}
/// <summary>
/// Resets the Value
/// </summary>
public override void ResetValue(object component)
{
((Dictionary<string, TestResultValue>)component)[base.Name].Value = string.Empty;
}
/// <summary>
/// Sets the value
/// </summary>
public override void SetValue(object component, object value)
{
((Dictionary<string, TestResultValue>)component)[base.Name].Value = value.ToString();
}
/// <summary>
/// Gets whether the value should be serialized
/// </summary>
public override bool ShouldSerializeValue(object component)
{
return false;
}
#endregion Methods
//---------------------------------------------------------------------------------------------------------------------------
}
The main properties to look at on this class are GetValue and SetValue. Here you can see the component being casted as a dictionary and the value of the key inside it being Set or retrieved. Its important that the dictionary in this class is the same type in the Row wrapper class otherwise the cast will fail. When the descriptor is created the key (property name) is passed in and is used to query the dictionary to get the correct value.
Taken from my blog at:
ICustomTypeDescriptor Implementation for dynamic properties
You should look into DependencyObjects as used by WPF these follow a similar pattern whereby properties can be assigned at runtime. As mentioned above this ultimately points towards using a hash table.
One other useful thing to have a look at is CSLA.Net. The code is freely available and uses some of the principles\patterns it appears you are after.
Also if you are looking at sorting and filtering I'm guessing you're going to be using some kind of grid. A useful interface to implement is ICustomTypeDescriptor, this lets you effectively override what happens when your object gets reflected on so you can point the reflector to your object's own internal hash table.
As a replacement for some of orsogufo's code, because I recently went with a dictionary for this same problem myself, here is my [] operator:
public string this[string key]
{
get { return properties.ContainsKey(key) ? properties[key] : null; }
set
{
if (properties.ContainsKey(key))
{
properties[key] = value;
}
else
{
properties.Add(key, value);
}
}
}
With this implementation, the setter will add new key-value pairs when you use []= if they do not already exist in the dictionary.
Also, for me properties is an IDictionary and in constructors I initialize it to new SortedDictionary<string, string>().
I'm not sure what your reasons are, and even if you could pull it off somehow with Reflection Emit (I' not sure that you can), it doesn't sound like a good idea. What is probably a better idea is to have some kind of Dictionary and you can wrap access to the dictionary through methods in your class. That way you can store the data from the database in this dictionary, and then retrieve them using those methods.
Why not use an indexer with the property name as a string value passed to the indexer?
Couldn't you just have your class expose a Dictionary object? Instead of "attaching more properties to the object", you could simply insert your data (with some identifier) into the dictionary at run time.
If it is for binding, then you can reference indexers from XAML
Text="{Binding [FullName]}"
Here it is referencing the class indexer with the key "FullName"

Store generic data in a non-generic class

I have a DataGridView that I want to use to store generic data. I want to keep a typed data list in the DataGridView class so that all of the sorts, etc. can be handled internally. But I don't want to have to set the type on the DataGridView since I won't know the data type until the InitializeData method is called.
public class MyDataGridView : DataGridView {
private List<T> m_data;
public InitializeData<T>(List<T> data) {
m_data = data;
}
... internal events to know when the datagrid wants to sort ...
m_data.Sort<T>(...)
}
Is this possible? If so, how?
If you won't know the type until you call InitializeData, then the type clearly can't be a compile-time part of the object.
Do you know everything you need to know about the sorting when you call InitializeData<T>? If so, how about you do something like:
private IList m_data;
private Action m_sorter;
public InitializeData<T>(List<T> data)
{
m_data = data;
// This captures the data variable. You'll need to
// do something different if that's not good enough
m_sorter = () => data.Sort();
}
Then when you need to sort later, you can just call m_sorter().
If you might sort on different things, you could potentially change it from an Action to Action<string> or whatever you'd need to be able to sort on.
If Jon's answer isn't sufficient, here's a more general (but more involved, and probably somewhat more confusing) approach:
/// <summary>
/// Allows a list of any type to be used to get a result of type TResult
/// </summary>
/// <typeparam name="TResult">The result type after using the list</typeparam>
interface IListUser<TResult>
{
TResult Use<T>(List<T> list);
}
/// <summary>
/// Allows a list of any type to be used (with no return value)
/// </summary>
interface IListUser
{
void Use<T>(List<T> list);
}
/// <summary>
/// Here's a class that can sort lists of any type
/// </summary>
class GenericSorter : IListUser
{
#region IListUser Members
public void Use<T>(List<T> list)
{
// do generic sorting stuff here
}
#endregion
}
/// <summary>
/// Wraps a list of some unknown type. Allows list users (either with or without return values) to use the wrapped list.
/// </summary>
interface IExistsList
{
TResult Apply<TResult>(IListUser<TResult> user);
void Apply(IListUser user);
}
/// <summary>
/// Wraps a list of type T, hiding the type itself.
/// </summary>
/// <typeparam name="T">The type of element contained in the list</typeparam>
class ExistsList<T> : IExistsList
{
List<T> list;
public ExistsList(List<T> list)
{
this.list = list;
}
#region IExistsList Members
public TResult Apply<TResult>(IListUser<TResult> user)
{
return user.Use(list);
}
public void Apply(IListUser user)
{
user.Use(list);
}
#endregion
}
/// <summary>
/// Your logic goes here
/// </summary>
class MyDataGridView
{
private IExistsList list;
public void InitializeData<T>(List<T> list)
{
this.list = new ExistsList<T>(list);
}
public void Sort()
{
list.Apply(new GenericSorter());
}
}
You should define delgates or an interface for any generic operations you need to perform at runtime. As Jon Skeet mentioned, you can't strongly-type your data grid if you don't know the types at compile time.
This is the way the framework does it. For example:
Array.Sort();
Has a few ways it can be used:
Send it an array of objects that implement IComparable or IComparable<T>
Send in a second parameter, which is a class that implements IComparer or IComparer<T>. Used to compare the objects for sorting.
Send in a second parameter, which is a Comparison<T> delegate that can be used to compare objects in the array.
This is an example of how you approach the problem. At its most basic level, your scenario can be solved by a strategy pattern, which is what Array.Sort() does.
If you need to sort by things dynamically at run time, I would create an IComparer class that takes the column you want to sort by as an argument in its constructor. Then in your compare method, use that column as the sort type.
Here is an example of how you would do it using some basic example classes. Once you have these classes set up, then you'd pass both into your data grid and use them where appropriate.
public class Car
{
public string Make { get; set; }
public string Model { get; set; }
public string Year { get; set; }
}
public class CarComparer : IComparer
{
string sortColumn;
public CarComparer(string sortColumn)
{
this.sortColumn = sortColumn;
}
public int Compare(object x, object y)
{
Car carX = x as Car;
Car carY = y as Car;
if (carX == null && carY == null)
return 0;
if (carX != null && carY == null)
return 1;
if (carY != null && carX == null)
return -1;
switch (sortColumn)
{
case "Make":
return carX.Make.CompareTo(carY.Make);
case "Model":
return carX.Model.CompareTo(carY.Model);
case "Year":
default:
return carX.Year.CompareTo(carY.Year);
}
}
}

Categories

Resources