VBForums >
.NET >
C# > [RESOLVED] [2.0] follow up question to jmcilhinney...about Type class
Click to See Complete Forum and Search --> : [RESOLVED] [2.0] follow up question to jmcilhinney...about Type class
bnathvbdotnet
Apr 24th, 2006, 10:40 AM
Jm,
You gave me an example ...
Code:
Type typ1 = typeof(string);
string str = "Hello World";
Type typ2 = str.GetType();
I understand by getting Type object we can get more details like the methods, member infor, attributes etc..but under what circumstances do we need to know those details??
can you point to me any example code that reads more details of an object using Type??
thanks
nath
sunburnt
Apr 24th, 2006, 03:18 PM
Here is an example from a project of mine.
This function takes any number of parameters of varying types, and adds text to a Rich Text Box. It needs to find out the type of each object passed in order to decide what action to take -- ie, if it's a string, add it to the text property; if it's a color/font, change the currently selected color/font respectively.
public void WriteTextF(params object[] objs)
{
Type type;
Color color = Color.White;
Font font = new Font("Courier New",8.25f);
for(int i = 0; i < objs.Length; i++)
{
type = objs[i].GetType();
if (type == typeof(string))
{
// write text to textbox
RTB.SelectionStart = RTB.Text.Length;
RTB.SelectionLength = 0;
RTB.SelectionFont = font;
RTB.SelectionColor = color;
RTB.SelectedText = (string)(objs[i]);
RTB.SelectionStart = RTB.Text.Length;
}
//update color choice
else if (type == typeof(Color))
{
color = (Color)(objs[i]);
}
//update font choice
else if (type == typeof(Font))
{
font = (Font)(objs[i]);
}
// bad type! bad!
else
{
//throw new Exception("Unsupported Type");
}
}
The main concept is that the GetType() function is virtual -- ie, if I have a class "base," and a class "derived" which is derived from base, and I do something like the following:
derived d = new derived();
base b = d;
Console.WriteLine(b.GetType().ToString());
The output would tell me that 'b' is actually a derived object.
Hope this helps.
jmcilhinney
Apr 24th, 2006, 05:36 PM
There are also existing properties and methods in the Framework that use the Type class, for instance the DataType property of the DataColumn class, which indicates what type of data the column can contain.
vbforums.com
Copyright Internet.com Inc., All Rights Reserved.