Create variable of base types

N

Nick Weekes

Im trying to create a variable that can store all possible simple C#
types. This is so I can assign the type to a database column,
regardless of whether its string, int, bool etc. But, Id rather not
cast a string and switch the value, that seems a bit redundant.

So an example would be:

//
SimpleBaseTypes MyType;
MyType = bool;
MyDatabaseColumn.Type = MyType;
//

Is this possible or am I going about this in the wrong way?

Cheers all,

Nick
 
G

Guest

Hi,

The father of all the types is the "object" type, so you can assign whatever
you like to it. The problem is that after the assignation the variable is
cast to object and lost the original type, so if you ask for the type it will
say "object".

C# version 2.0 includes templates that will allow you to do this like C++.

Best regards
Salva
 
I

Ignacio Machin \( .NET/ C# MVP \)

Hi,

What you want is done alreayd, Object is the ancestor of ALL the types,
in fact DataTable.Rows[x][ColumnName] is an object this allow you to assign
it no matter the real type fo the column.

cheers,
 
J

Jon Skeet [C# MVP]

Salvador said:
The father of all the types is the "object" type, so you can assign
whatever you like to it. The problem is that after the assignation
the variable is cast to object and lost the original type, so if you
ask for the type it will say "object".

No, no type information is lost. For instance:

using System;

class Test
{
static void Main()
{
int i = 5;
object o = i;

Console.WriteLine (o.GetType().FullName);
}
}

will print "System.Int32", not "System.Object".
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top