about typeof

  • Thread starter Thread starter Tony Johansson
  • Start date Start date
T

Tony Johansson

Hello!

If this statement below is to return true does this mean that object myObj
must have exactly the same type as MyClass.
I have tested this and for me it must be the same.
I just want to make sure with you that you agree with me?
If (myObj.GetType() == typeof(MyClass)
{
....
}
 
Yes; that is fine and means *exactly* this type, as opposed to "this
type or a subclass" (for "is"/"as")

Marc
 
Hello!

If this statement below is to return true does this mean that object myObj
must have exactly the same type as MyClass.
I have tested this and for me it must be the same.
I just want to make sure with you that you agree with me?
If (myObj.GetType() == typeof(MyClass)
{
...



}- Hide quoted text -

- Show quoted text -

It menas that both have to be the very same types.
You can use IS if you want to know if you can cast one type into the
other, this mean interface implementation or inheritance.
 
Just a side note, I personally I like to use
“object.ReferenceEquals()” when testing for object identity:

if (object.ReferenceEquals(myObj.GetType(), typeof(MyClass)))

I feel that by doing this, I am making it clear what I am doing.

In the case of the “Type” class, this does not make any difference but
I prefer this syntax anyway. Of course, others will disagree so this
is just my opinion.

Thanks.
 

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

Back
Top