Zach Smith
Zach Smith

Reputation: 8961

C#: What does it mean to use a variable like a type?

I'm new to C#, coming from a Javascript background (so 'typing' is quite new to me).

What does the warning "... is a variable but is used like a type" mean?

I have the following code within a static function called test:

var activeCell = new ExcelReference(1, 1);
Type type = typeof(activeCell);

Upvotes: 3

Views: 13880

Answers (2)

yan yankelevich
yan yankelevich

Reputation: 945

Quite easy in fact. typeof is used with a Class, Interface etc name, meanwhile for what you want you will need the GetType function.

Example :

public class MyObject
{
    public static Type GetMyObjectClassType()
    {
        return typeof(MyObject);
    }
    public static Type GetMyObjectInstanceType(MyObject someObject)
    {
        return someObject.GetType();
    }

    public static Type GetAnyClassType<GenericClass>()
    {
        return typeof(GenericClass);
    }
    public static Type GetAnyObjectInstanceType(object someObject)
    {
        return someObject.GetType();
    }

    public void Demo()
    {
        var someObject = new MyObject();
        Console.WriteLine(GetMyObjectClassType()); // will write the type of the class MyObject
        Console.WriteLine(GetMyObjectInstanceType(someObject)); // will write the type of your instance of MyObject called someObject
        Console.WriteLine(GetAnyClassType<MyObject>()); // will write the type of any given class, here MyObject
        Console.WriteLine(GetAnyClassType<System.Windows.Application>()); //  will write the type of any given class, here System.Windows.Application
        Console.WriteLine(GetAnyObjectInstanceType("test")); // will write the type of any given instance, here some string called "test"
        Console.WriteLine(GetAnyObjectInstanceType(someObject)); // will write the type of any given instance, here your instance of MyObject called someObject
    }
}

Upvotes: 2

RusArt
RusArt

Reputation: 576

You can use typeof only with a type, for example Type type = typeof(ExcelReference);

If you want to know what type is this variable use Type type = activeCell.GetType();

Upvotes: 9

Related Questions