question

BitSmithy-4663 avatar image
0 Votes"
BitSmithy-4663 asked PeterFleischer-3316 answered

Type as a method parameter

I am trying such code, but this code is marked by VS as error. I want to pass class as a parameter to the method. Is any way to do it properly?


public string MyMethod(Object dataObject, Type dataType)
{

         if (dataObject is dataType obj)
         {
         //some code here

         }
     }

windows-uwp
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

mrlacey avatar image
0 Votes"
mrlacey answered

You could use a generic method for this:

public string MyMethod<T>(T dataObject)
{
    // some code here
}


The type is passed as T and (under the hood) the compiler creates appropriate overloads for you to pass what need.

5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

danielescipioni avatar image
0 Votes"
danielescipioni answered BitSmithy-4663 commented

It seems to me that you have to check if dataObject is of the given dataType at runtime , so I would go like that

public string MyMethod(object dataObject, Type dataType)
{
    if (dataType.IsInstanceOfType(dataObject))
    {
        //some code here
    }
}

· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

This answer is acceptable too, but MQA blocks setting two accepted answers.

0 Votes 0 ·
PeterFleischer-3316 avatar image
0 Votes"
PeterFleischer-3316 answered

Hi, the construct "if (dataObject is dataType obj)" assume that "obj" get the value of dataObject if the type of dataObject is dataType. In this case you can use your variable "obj" inside scope "if". Try following code:

   private void Sub1<dataType>(Object dataObject)
   {
     if (dataObject is dataType obj)
     {
       var result = obj;
       Console.WriteLine(result.ToString());
     }
   }
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.