Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

Welcome to the new platform of Programmer's Heaven! We apologize for the inconvenience caused, if you visited us from a broken link of the previous version. The main reason to move to a new platform is to provide more effective and collaborative experience to you all. Please feel free to experience the new platform and use its exciting features. Contact us for any issue that you need to get clarified. We are more than happy to help you.

Knowing the type of an object in c#...

premarthapremartha Posts: 12Member
I was going through the .NET documentation and read the following...

One of the most important features of the CLR is its type safety. The CLR always knows what type an object is. You can always discover an object's exact type by calling the GetType method. Since this method is non-virtual, a type cannot ever spoof another type: a Foo type cannot override the GetType method and return that it is a Bar type, for example.

As every class in C#, like Java is implicitly inherited by Object and getType is a method defined by Object. in the above quoted text, i cudnt understand what they mean by.."[b][red]Since this method is non-virtual, a type cannot ever spoof another type: a Foo type cannot override the GetType method and return that it is a Bar type, for example.[/red][/b]"

Can anybody please explain to me with the help of an example what they mean by method being non-virtual? what could have been the result if this method would have declared as virtual in Object??

Comments

  • weiccoweicco Posts: 950Member
    : Can anybody please explain to me with the help of an example what they mean by method being non-virtual? what could have been the result if this method would have declared as virtual in Object??
    :

    [code]
    class MyBaseClass
    {
    public /*Non-virtual*/ string GetName() { return "Foo"; }
    public virtual string GetVirtualName() { return "Foo"; }
    }

    MyBaseClass c = new MyBaseClass();
    c.GetName() // returns "Foo"
    c.GetVirtualName() // returns "Foo"

    class MyDerivingClass : MyBaseClass
    {
    public override string GetVirtualName() { return "Bar"; }
    }

    MyDerivingClass c = new MyDerivingClass();
    c.GetName() // returns "Foo"
    g.GetVirtualName() // returns now "Bar" since deriving class overrides it
    [/code]
Sign In or Register to comment.