Newbie: When to use typeof() function

  • Thread starter Thread starter GiJeet
  • Start date Start date
G

GiJeet

Hello, I see the use of typeof() function often when I'm reading code
but I'm not sure when I would need to use it. I understand it returns
the type of a type. huh? It's kind of confusing. Can someone provide
an example of when I would need to know the type of something and
would need to use typeof(). Thanks.

G
 
GiJeet said:
Hello, I see the use of typeof() function often when I'm reading code
but I'm not sure when I would need to use it. I understand it returns
the type of a type. huh? It's kind of confusing. Can someone provide
an example of when I would need to know the type of something and
would need to use typeof(). Thanks.


DataColumn foo = new DataColumn("foo", typeof(string));
 
GiJeet said:
Hello, I see the use of typeof() function often when I'm reading code
but I'm not sure when I would need to use it. I understand it returns
the type of a type. huh? It's kind of confusing. Can someone provide
an example of when I would need to know the type of something and
would need to use typeof(). Thanks.

G

An example of when I use it is in creating an XmlSerializer instance to
serialize an object. If you have an object to be serialized, you could do:

XmlSerializer s = new XmlSerializer(anObject.GetType());

but I have tended to do:

XmlSerializer s = new XmlSerializer(TypeOf(SomeClassName));

as this constructor needs a type as the argument.
 
Hello, I see the use of typeof() function often when I'm reading code
but I'm not sure when I would need to use it. I understand it returns
the type of a type. huh?  It's kind of confusing.  Can someone provide
an example of when I would need to know the type of something and
would need to use typeof().  Thanks.

G

It doesn't return the type of a type. Think of it as returning the
type of a variable.

The two examples given are good examples: if you are creating a
DataColumn you need to know what data type goes in the column (string,
int, deecimal...)

Since you can't use the keyword "string" (because that's a declarator)
you say "typeof(string)". That returns the System.Type "String".

Hope that helps.

Tom P.
 
Thanks for the examples but I guess now my question is WHY do I need
to get the type of a type? Is it a run-time thing? I mean, we know
the types at design time.
 
Thanks for the examples but I guess now my question is WHY do I need
to get the type of a type? Is it a run-time thing? I mean, we know
the types at design time.

Some functions require a Type as a parameter. It's just the way the language
was designed that doesn't allow you to do this:

DataColumn foo = new DataColumn("foo", string);

and instead requires you to do this:

DataColumn foo = new DataColumn("foo", typeof(string));
 
Some functions require a Type as a parameter. It's just the way the language
was designed that doesn't allow you to do this:

    DataColumn foo = new DataColumn("foo", string);

and instead requires you to do this:

    DataColumn foo = new DataColumn("foo", typeof(string));

This assumes the keyword "string" is a type, it's not.

It's what is called a "declarator", it declares that some other
variable is of type "string".

OK, say you are putting LoanNumbers into a column in a datastore. When
you create the LoanNumber variable you have to declare that it's a
string:
string LoanNumber;

If you just put the old VB:
Dim LoanNumber
....you'd never know what type LoanNumber was. C# makes you "declare"
what type of data a variable is going to contain.

In other words there's a difference between:
string LoanNumber;
....and...
System.Type.String

Since in method calls like
DataColumn foo = new DataColumn("foo", typeof(string));

you are not declaring a variable, you can't use the variable
declarator "string". In that case you have to simply tell it the
System.Type of data (not variable) that the DataColumn will contain.

It's like the difference between a "class" and an "object". A class is
a description of what you want to do, an object is when you create and
use the class.

Hope that helps.

Tom P.
 
This assumes the keyword "string" is a type, it's not.

It's what is called a "declarator", it declares that some other
variable is of type "string".

OK, say you are putting LoanNumbers into a column in a datastore. When
you create the LoanNumber variable you have to declare that it's a
string:
string LoanNumber;

If you just put the old VB:
Dim LoanNumber
...you'd never know what type LoanNumber was. C# makes you "declare"
what type of data a variable is going to contain.

In other words there's a difference between:
string LoanNumber;
...and...
System.Type.String

Since in method calls like
DataColumn foo = new DataColumn("foo", typeof(string));

you are not declaring a variable, you can't use the variable
declarator "string". In that case you have to simply tell it the
System.Type of data (not variable) that the DataColumn will contain.

It's like the difference between a "class" and an "object". A class is
a description of what you want to do, an object is when you create and
use the class.

hmmm....ok I'm trying to get my head around this. So whenever we can't
use a declarator we have to use the typeof() function?
 
Hello, I see the use of typeof() function often when I'm reading code
but I'm not sure when I would need to use it. I understand it returns
the type of a type. huh?

No really,it return an instance of a class that has info regarding the
type. Using the returned instance you can know the properties, method,
etc of the type.
You use it to know the details of a type.
 
Some functions require a Type as a parameter. It's just the way the
language
was designed that doesn't allow you to do this:

DataColumn foo = new DataColumn("foo", string);

and instead requires you to do this:

DataColumn foo = new DataColumn("foo", typeof(string));
This assumes the keyword "string" is a type, it's not.
It's what is called a "declarator", it declares that some other
variable is of type "string".

Huh? Are you telling me the second line of code won't work? You better tell
that to Visual Studio too, because it works just fine for me.

string is nothing more than a C# alias to System.String, which is a type.
Therefore, for all intents and purposes, string is a type, and can be used
as an argument to typeof().
 
string is just a *keyword* that express a type. typeof allows to return a
*variable* that symbolizes this type *name*.

Don't see this as returning the "type of a type" but as returning a type
variable for a type "literal" mentioned in your source code....

I'd use the word "instance" instead of "variable," personally.
 
hmmm....ok I'm trying to get my head around this. So whenever we can't
use a declarator we have to use the typeof() function?

Yes and No. That's like asking "So where I can't use a car I can use a
banana?" They are not interchangeable. They are two different things.

Since you can never pass a declarator, you'd always use typeof to pass
the type to a method.

And since you can't use System.Type to declare a variable you'll
always use the declarator to declare a variable.

Think of it as a person with a job. Say you drive a bus, you are a bus
driver, that's what you do. When someone asks what type of work do you
do, you tell them Bus Driver, because that's your job. Your job would
be System.Type.BusDriver and when you went to work they would refer to
you as BusDriver GiJeet.

Does that help?

Tom P.
 
hmmm....ok I'm trying to get my head around this. So whenever we can't
use a declarator we have to use the typeof() function?

No. What you need to look at is the declaration of the method you're
calling. If that method requires a parameter of type "System.Type," then you
need to provide a Type object. There are a couple of ways to do this. The
typeof() function is one of those ways, but it's kind of "hard-coded"
because you have to specify a specific type name in your code; you cannot
use a variable here. If you need to use a variable, then you want to call
the GetType() method directly on the variable. Every single variable has
this method because this method is defined on System.Object and every type
inherits from Object.

Looking at it the long way may help. We'll go back to the DataColumn
example. Let's look at the declaration of one of DataColumn's constructors:

public DataColumn (string columnName, Type dataType)

See the second argument? Type.

The following code snippets do the same thing:

Type t = typeof(string);
// t is now an instance of System.Type that knows all about the
System.String class
DataColumn foo = new DataColumn("foo", t);

===========

string s = "The contents of this string are irrelevant.";
Type t = s.GetType();
// t is now an instance of System.Type that knows all about the
System.String class
DataColumn foo = new DataColumn("foo", t);


You may be having problems wrapping your head around the concept of
meta-data. The Type class is all about meta-data.
 
[...]
Some functions require a Type as a parameter. It's just the way the  
language
was designed that doesn't allow you to do this:
    DataColumn foo = new DataColumn("foo", string);
and instead requires you to do this:
    DataColumn foo = new DataColumn("foo", typeof(string));
This assumes the keyword "string" is a type, it's not.

Yes, it is.  As Jeff points out, "string" is simply an alias for  
"System.String".  Both are type names, and using "typeof" with either  
returns the same Type instance, the one that corresponds to the type  
System.String.

Exactly, as you say at the end there is a difference between
System.String
....and ...
System.Type.String

"string" is not a System.Type object, it is an alias for a declarator
of type System.String

And you are right, both of them do return the same thing - a
System.Type.String object (as opposed to a System.String object).

No, it's not called that.  It's called a "type".

You may want to look up the C# grammar because it's a declaration
statement. You declare a variable like so:
string SomeString = "Characters";

Thus "string" is the type declarator, "SomeString" is called the
identifier, and "Characters" is called the initializer.

If you feel like pouring through it here's the MSDN page:http://
msdn.microsoft.com/en-us/library/aa664812.aspx

The section looks like this:
variable-declarator:
identifier
identifier = variable-initializer
[...]
In other words there's a difference between:
string LoanNumber;
...and...
System.Type.String

Yup, big difference.  The former compiles, and the latter doesn't.

Pete

The later most assuredly does compile, IF used correctly. Like I said
above, and you did bring up a point that makes the difference much
more apparent. There is a difference between:
System.String and System.Type.String

And each can be used, in an appropriate manner, they are not
interchangeable.

Tom P.
 
Exactly, as you say at the end there is a difference between
System.String
...and ...
System.Type.String
"string" is not a System.Type object, it is an alias for a declarator
of type System.String
And you are right, both of them do return the same thing - a
System.Type.String object (as opposed to a System.String object).

What the hell is a System.Type.String? Is it a .NET 3.5 thing? Because no
such thing exists in .NET 2.0.
 
What the hell is a System.Type.String? Is it a .NET 3.5 thing? Because no
such thing exists in .NET 2.0.

No, if you type System.Type. it does not show up in the intellisense
but I don't know another way of typing it. System.Type<String> might
be a little more correct but it's still not real. I mean a System.Type
instance that represents a String data type.

I didn't mean to confuse the issue.

Tom P.
 
No, if you type System.Type. it does not show up in the intellisense
but I don't know another way of typing it. System.Type<String> might
be a little more correct but it's still not real. I mean a System.Type
instance that represents a String data type.

There is no shorthand reference for it. You need to spell it out, like in
your last sentence.

This all goes back to my reply where I said that System.Type is all about
meta-data and it's hard to describe what Type is for to someone who doesn't
understand what meta-data is.
 
[...]
"string" is not a System.Type object, it is an alias for a declarator
of type System.String

You keep misusing that term "declarator".
And you are right, both of them do return the same thing - a
System.Type.String object (as opposed to a System.String object).

There is no such things as "System.Type.String".
You may want to look up the C# grammar because it's a declaration
statement.

I not only looked up the C# grammar, I posted an excerpt in my reply to  
you.  And it clearly states that the text "string" is called a "type", and  
not a "declarator" or "declaration statement.
You declare a variable like so:
string SomeString = "Characters";
Thus "string" is the type declarator,

No, it's not.
"SomeString" is called the
identifier, and "Characters" is called the initializer.

That's correct.
If you feel like pouring through it here's the MSDN page:http://
msdn.microsoft.com/en-us/library/aa664812.aspx
The section looks like this:
variable-declarator:
    identifier
    identifier   =   variable-initializer

I have the feeling you don't understand how to read the grammar  
description.  What the above means is that the thing called a  
"variable-declarator" can either be an "identifier", or an "identifier =  
variable-initializer".  In other words, in your example:

     string SomeString = "Characters";

The "variable-declarator" is this part:

     SomeString = "Characters";

The type isn't part of it at all.
[...]
In other words there's a difference between:
string LoanNumber;
...and...
System.Type.String
Yup, big difference.  The former compiles, and the latter doesn't.
Pete
The later most assuredly does compile, IF used correctly.

Please provide a concise-but-complete code example where  
"System.Type.String" compiles.
Like I said
above, and you did bring up a point that makes the difference much
more apparent. There is a difference between:
System.String and System.Type.String

That's true, but the difference is not what you seem to think it is.

Pete

OK, first off thank you for being this patient with me. I'm not trying
to be argumentative, I honestly thought what I had said was true (for
over 17 years, I "thought" I learned it as C++ grammar. So I've
apparently been misunderstanding this for much longer than you may
think.)
There is no such things as "System.Type.String".

Granted, I don't know the correct syntax for representing what I'm
trying to convey. Something like System.Type<string> but that may not
be correct either (I know it's not correct C# but it might convey the
idea better).

I'm trying to establish the difference between System.String and the
return object from typeof(string). In other words you cannot compile
the following:

if (System.String == typeof(string))
{
MessageBox.Show("They are equal!! Go figure!");
}

....because (to be fair to you and Jeff) the compiler will say
"System.String" is a type and can't be used that way. But you can do
this:

System.Type vartype = typeof(System.String);

I guess the distinction is, like most things in C#, case-sensitive.
"Type" is an actual C# object, "type" is the English word we use to
describe the kind of data the variable holds.

Tom P.
 
There is no shorthand reference for it. You need to spell it out, like in
your last sentence.

This all goes back to my reply where I said that System.Type is all about
meta-data and it's hard to describe what Type is for to someone who doesn't
understand what meta-data is.

As I hope you can see from my last exchange with Peter, I think I'm
getting it cleared up. I must apologize if I seem argumentative, I
don't mean to be. It's just that this is something that I've !known!
for years. I knew this like I know how code an "if" statement, I was
sure of it.

How do feel about my last attempt at discerning the difference:
....the distinction is, like most things in C#, case-sensitive.
"Type" is an actual C# object, "type" is the English word we use to
describe the kind of data the variable holds.

Tom P.
 
I'm trying to establish the difference between System.String and the
return object from typeof(string). In other words you cannot compile
the following:
if (System.String == typeof(string))
{
MessageBox.Show("They are equal!! Go figure!");
}

And this is just a learning experience for the C# programmer. You need to
know that the intent of the code above needs to be expressed as

if (myVar is string)
{
MessageBox.Show("myVar is a string.");
}

It's the same as needing to learing that the following C code is wrong:

if (myPointer == *someVar)
{
printf("...");
}

because ultimately you're comparing apples and oranges. (And before some
smarty-pants opens his mouth, someVar is not a **<type>....)
 
Back
Top