JSArrakis
JSArrakis

Reputation: 799

C# Error when attempting to pass Type as parameter when method requires a type

As a test case Ive created the following very simple method:

public static object TestMethod(Type t)
    {
        return t;
    }

For the type I am attempting to pass through it, I have created a very basic class also as a test:

public class TestClass
    {
        public string name { get; set; }
    }

Finally I am attempting to call the method normally:

TestClass sample = TestMethod(TestClass);

However it seems that when TestClass is passed as a parameter for TestMethod, I receive the error: "'TestClass' is a type, which is not valid in the given context."

This makes no sense to me as the parameter required IS a type.

Upvotes: 1

Views: 231

Answers (2)

user6996876
user6996876

Reputation:

Try this:

TestClass sample = (TestClass)TestMethod(typeof(TestClass)); //notice the cast because the method is returning an object

Technical debt

The above compiles but throws an invalid cast exception: what a senior professional should tell you is that you need to change also this

public static object TestMethod(Type t)
{
    return Activator.CreateInstance(t); 
}

Upvotes: 0

lokusking
lokusking

Reputation: 7456

To use your method, do it like this

TestClass sample = (TestClass)TestMethod(typeof(TestClass));

Your Result will be an Type and not TestClass so you will get a RuntimeException.

On already existing instances use

TestMethod(testClassInstance.GetType())

But what are your trying to achieve?

Upvotes: 2

Related Questions