1

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.

JSArrakis
  • 777
  • 1
  • 9
  • 22
  • 1
    typeof or GetType() will work, but the better question is what exactly are you trying to accomplish? This seems like a prime opportunity for generics. – Parrish Husband Aug 06 '16 at 17:30

2 Answers2

2

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?

lokusking
  • 7,396
  • 13
  • 38
  • 57
  • @MachineLearning the last line of this answer is the important point here. There are almost definitely better ways of achieving what it seems OP is trying to do. – Parrish Husband Aug 06 '16 at 17:44
  • 1
    Touche, but do you know what technical debt is? ;) – Parrish Husband Aug 06 '16 at 17:48
  • @lokusking The end goal was to pass in a json string and a class full of properties in which I deserialize the json string and fill the class with the appropriate values from a response of the API I am calling – JSArrakis Aug 06 '16 at 17:49
  • 1
    http://stackoverflow.com/questions/7895105/deserialize-json-with-c-sharp – Parrish Husband Aug 06 '16 at 17:51
  • @JSArrakis pls, consider editing your question if you need to better clarify it... –  Aug 06 '16 at 17:51
  • @MachineLearning My question was answered. My deserialization was not the question, only why when passing a Type I was receiving an error. The scope of the question was simply that, and it was answered. I am not looking for a better way to do the rest of the method that I am writing. – JSArrakis Aug 06 '16 at 19:12
0

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); 
}