views:

50

answers:

3
+1  Q: 

Type-ing quesion

Hey everyone, I have a few tables in my database and they all contain a different inherited type of a DataRow.

In addition I have a class that is supposed to handle some things in my DataGrid (My database Tables are connected to DataGrids).

In order to do that, one of the methods in this DataGrid handler has to cast the rows to the exact inherited type of a DataRow.

something like this: (TempDataRow as DataRowTypeThatInheritsFromRegularDataRow).SpecialParameter = something;

In order to do that, I have to pass the method the inherited DataRow type, so it will know how to do the casting.

The method will generally look like this:

public void DoSomthing(DataRowType Type) { (TempDataRow as Type).SpecialParameter = something; }

the thing is I don't know how to pass the type. Regular 'Type' type does not compile. and if I pass just 'DataRow' it won't know how to do the casting.

any suggestions? Thanks.

A: 

You could use:

TempDataRow as Type.GetType("DataRowTypeName")
JoelHess
That won't compile. The language doesn't work like that.
Dave Markle
+1  A: 

If you are using C# 4.0, then have you considered the use of the 'dynamic' type?

dynamic row = getDataRow();
doSomething( row );

public void doSomething( DataRowTypeThatInheritsFromRegularDataRow row )
{
    // <insert code here>
}

public void doSomething( SomeOtherDataRowType row )
{
    // <insert code here>
}

This example should choose at run-time which function to call, based upon what getDataRow() actually returns.

For further reading of dynaminc see msdn

TK
A: 

There are a number of ways you could do this.

First, you could find a common base class or interface that all types share, and then have DoSomething() take that base class or interface, or if you want to be totally dynamic, you could use reflection. It's hard to tell you how to do it, because you haven't given any concrete example:

using System.Reflection;
...
public void DoSomething(object foo) {
    var dataType = foo.GetType();

    type.GetProperty("SomeDynamicName").SetValue(foo, someOtherValue);
}

(though if you were using C# 4.0, as TK points out, you could just use the dynamic type and be done with it!)

Dave Markle