Passing a Dynamic Type as a Parameter to a Method in C#2019 Community Moderator ElectionPassing arguments to C# generic new() of templated typeWhat is the difference between String and string in C#?Hidden Features of C#?Cast int to enum in C#Create Generic method constraining T to an EnumHow do I enumerate an enum in C#?What are the correct version numbers for C#?Type Checking: typeof, GetType, or is?Pass Method as Parameter using C#Deserialize JSON into C# dynamic object?Google Gson - deserialize list<class> object? (generic type)

Could the Saturn V actually have launched astronauts around Venus?

What exactly is this small puffer fish doing and how did it manage to accomplish such a feat?

Who is flying the vertibirds?

How to write cleanly even if my character uses expletive language?

How to make healing in an exploration game interesting

An inequality of matrix norm

Define, (actually define) the "stability" and "energy" of a compound

Min function accepting varying number of arguments in C++17

Charles Hockett - 'F' article?

Why is the President allowed to veto a cancellation of emergency powers?

In a future war, an old lady is trying to raise a boy but one of the weapons has made everyone deaf

What do Xenomorphs eat in the Alien series?

How to explain that I do not want to visit a country due to personal safety concern?

Existence of subset with given Hausdorff dimension

How to simplify this time periods definition interface?

What is the significance behind "40 days" that often appears in the Bible?

SOQL: Populate a Literal List in WHERE IN Clause

What did Alexander Pope mean by "Expletives their feeble Aid do join"?

Why do passenger jet manufacturers design their planes with stall prevention systems?

How to use deus ex machina safely?

Did Ender ever learn that he killed Stilson and/or Bonzo?

Have researchers managed to "reverse time"? If so, what does that mean for physics?

If I can solve Sudoku can I solve Travelling Salesman Problem(TSP)? If yes, how?

Why doesn't the EU now just force the UK to choose between referendum and no-deal?



Passing a Dynamic Type as a Parameter to a Method in C#



2019 Community Moderator ElectionPassing arguments to C# generic new() of templated typeWhat is the difference between String and string in C#?Hidden Features of C#?Cast int to enum in C#Create Generic method constraining T to an EnumHow do I enumerate an enum in C#?What are the correct version numbers for C#?Type Checking: typeof, GetType, or is?Pass Method as Parameter using C#Deserialize JSON into C# dynamic object?Google Gson - deserialize list<class> object? (generic type)










-2















I have a C# console app. This app is built to work with some existing, strongly-typed code. I need to convert the strongly-typed objects to something more dynamic. In an attempt to do this, I've decided to use generics. However, I have one thing that I can't figure out.



If I have a Type, how do I pass that to a method and use it? With generics, a compile-time type is required. However, my type is generated a run-time. How do I do this? As shown in the contrived example below, I basically want to convert from one a compile-time known type to a type generated at runtime. In the following two lines, I want to use the type generated at runtime in place of T.



var ingredient1 = BlendableItem.ConvertTo<T>(strawberry);
var ingredient2 = BlendableItem.ConvertTo<T>(blueberry);


In an effort to drive the concept home, here is my contrived example.



public class MyConsoleApp

private dynamic blender = null;

static void Main(string[] args)

// Identify the types of items to blend together from the config file
// Imaging for this example this value is "Fruit"
var typeToUse = ConfigurationManager.AppSettings["TypeToUse"];

// Create a new Blender<typeToUse>
var blenderType = typeof(Blender<>);
var newBlenderType = blenderType.MakeGenericType(typeToUse);
blender = Activator.CreateInstance(newBlenderType);

// Get the items to blend
var strawberry = new Strawberry();
var blueberry = new Blueberry();

// Convert items to "newBlenderType"
var ingredient1 = BlendableItem.ConvertTo<T>(strawberry);
var ingredient2 = BlendableItem.ConvertTo<T>(blueberry);

var ingredients = new List<dynamic>()
ingredient1,
ingredient2
;

var result = blender.Blend(ingredients);



public class Strawberry : BlendableItem


public class Blueberry : BlendableItem


public class Blender<T> where T : BlendableItem

public bool Blend(List<T> ingredients)

// do stuff
return true;



public class BlendableItem

public static T ConvertTo<T>(Fruit fruit)

object result = null;
// move properties from fruit to result
return result;




How do I pass a type that's generated at run-time to a method that uses generics?



Thank you










share|improve this question






















  • Possible duplicate of Passing arguments to C# generic new() of templated type

    – Heretic Monkey
    Mar 6 at 19:53















-2















I have a C# console app. This app is built to work with some existing, strongly-typed code. I need to convert the strongly-typed objects to something more dynamic. In an attempt to do this, I've decided to use generics. However, I have one thing that I can't figure out.



If I have a Type, how do I pass that to a method and use it? With generics, a compile-time type is required. However, my type is generated a run-time. How do I do this? As shown in the contrived example below, I basically want to convert from one a compile-time known type to a type generated at runtime. In the following two lines, I want to use the type generated at runtime in place of T.



var ingredient1 = BlendableItem.ConvertTo<T>(strawberry);
var ingredient2 = BlendableItem.ConvertTo<T>(blueberry);


In an effort to drive the concept home, here is my contrived example.



public class MyConsoleApp

private dynamic blender = null;

static void Main(string[] args)

// Identify the types of items to blend together from the config file
// Imaging for this example this value is "Fruit"
var typeToUse = ConfigurationManager.AppSettings["TypeToUse"];

// Create a new Blender<typeToUse>
var blenderType = typeof(Blender<>);
var newBlenderType = blenderType.MakeGenericType(typeToUse);
blender = Activator.CreateInstance(newBlenderType);

// Get the items to blend
var strawberry = new Strawberry();
var blueberry = new Blueberry();

// Convert items to "newBlenderType"
var ingredient1 = BlendableItem.ConvertTo<T>(strawberry);
var ingredient2 = BlendableItem.ConvertTo<T>(blueberry);

var ingredients = new List<dynamic>()
ingredient1,
ingredient2
;

var result = blender.Blend(ingredients);



public class Strawberry : BlendableItem


public class Blueberry : BlendableItem


public class Blender<T> where T : BlendableItem

public bool Blend(List<T> ingredients)

// do stuff
return true;



public class BlendableItem

public static T ConvertTo<T>(Fruit fruit)

object result = null;
// move properties from fruit to result
return result;




How do I pass a type that's generated at run-time to a method that uses generics?



Thank you










share|improve this question






















  • Possible duplicate of Passing arguments to C# generic new() of templated type

    – Heretic Monkey
    Mar 6 at 19:53













-2












-2








-2








I have a C# console app. This app is built to work with some existing, strongly-typed code. I need to convert the strongly-typed objects to something more dynamic. In an attempt to do this, I've decided to use generics. However, I have one thing that I can't figure out.



If I have a Type, how do I pass that to a method and use it? With generics, a compile-time type is required. However, my type is generated a run-time. How do I do this? As shown in the contrived example below, I basically want to convert from one a compile-time known type to a type generated at runtime. In the following two lines, I want to use the type generated at runtime in place of T.



var ingredient1 = BlendableItem.ConvertTo<T>(strawberry);
var ingredient2 = BlendableItem.ConvertTo<T>(blueberry);


In an effort to drive the concept home, here is my contrived example.



public class MyConsoleApp

private dynamic blender = null;

static void Main(string[] args)

// Identify the types of items to blend together from the config file
// Imaging for this example this value is "Fruit"
var typeToUse = ConfigurationManager.AppSettings["TypeToUse"];

// Create a new Blender<typeToUse>
var blenderType = typeof(Blender<>);
var newBlenderType = blenderType.MakeGenericType(typeToUse);
blender = Activator.CreateInstance(newBlenderType);

// Get the items to blend
var strawberry = new Strawberry();
var blueberry = new Blueberry();

// Convert items to "newBlenderType"
var ingredient1 = BlendableItem.ConvertTo<T>(strawberry);
var ingredient2 = BlendableItem.ConvertTo<T>(blueberry);

var ingredients = new List<dynamic>()
ingredient1,
ingredient2
;

var result = blender.Blend(ingredients);



public class Strawberry : BlendableItem


public class Blueberry : BlendableItem


public class Blender<T> where T : BlendableItem

public bool Blend(List<T> ingredients)

// do stuff
return true;



public class BlendableItem

public static T ConvertTo<T>(Fruit fruit)

object result = null;
// move properties from fruit to result
return result;




How do I pass a type that's generated at run-time to a method that uses generics?



Thank you










share|improve this question














I have a C# console app. This app is built to work with some existing, strongly-typed code. I need to convert the strongly-typed objects to something more dynamic. In an attempt to do this, I've decided to use generics. However, I have one thing that I can't figure out.



If I have a Type, how do I pass that to a method and use it? With generics, a compile-time type is required. However, my type is generated a run-time. How do I do this? As shown in the contrived example below, I basically want to convert from one a compile-time known type to a type generated at runtime. In the following two lines, I want to use the type generated at runtime in place of T.



var ingredient1 = BlendableItem.ConvertTo<T>(strawberry);
var ingredient2 = BlendableItem.ConvertTo<T>(blueberry);


In an effort to drive the concept home, here is my contrived example.



public class MyConsoleApp

private dynamic blender = null;

static void Main(string[] args)

// Identify the types of items to blend together from the config file
// Imaging for this example this value is "Fruit"
var typeToUse = ConfigurationManager.AppSettings["TypeToUse"];

// Create a new Blender<typeToUse>
var blenderType = typeof(Blender<>);
var newBlenderType = blenderType.MakeGenericType(typeToUse);
blender = Activator.CreateInstance(newBlenderType);

// Get the items to blend
var strawberry = new Strawberry();
var blueberry = new Blueberry();

// Convert items to "newBlenderType"
var ingredient1 = BlendableItem.ConvertTo<T>(strawberry);
var ingredient2 = BlendableItem.ConvertTo<T>(blueberry);

var ingredients = new List<dynamic>()
ingredient1,
ingredient2
;

var result = blender.Blend(ingredients);



public class Strawberry : BlendableItem


public class Blueberry : BlendableItem


public class Blender<T> where T : BlendableItem

public bool Blend(List<T> ingredients)

// do stuff
return true;



public class BlendableItem

public static T ConvertTo<T>(Fruit fruit)

object result = null;
// move properties from fruit to result
return result;




How do I pass a type that's generated at run-time to a method that uses generics?



Thank you







c# generics dynamic






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 6 at 19:51









user687554user687554

1,249104183




1,249104183












  • Possible duplicate of Passing arguments to C# generic new() of templated type

    – Heretic Monkey
    Mar 6 at 19:53

















  • Possible duplicate of Passing arguments to C# generic new() of templated type

    – Heretic Monkey
    Mar 6 at 19:53
















Possible duplicate of Passing arguments to C# generic new() of templated type

– Heretic Monkey
Mar 6 at 19:53





Possible duplicate of Passing arguments to C# generic new() of templated type

– Heretic Monkey
Mar 6 at 19:53












0






active

oldest

votes











Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55031154%2fpassing-a-dynamic-type-as-a-parameter-to-a-method-in-c-sharp%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























0






active

oldest

votes








0






active

oldest

votes









active

oldest

votes






active

oldest

votes















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55031154%2fpassing-a-dynamic-type-as-a-parameter-to-a-method-in-c-sharp%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

AWS Lex not identifying response if by a variable The 2019 Stack Overflow Developer Survey Results Are In Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern) The Ask Question Wizard is Live! Data science time! April 2019 and salary with experienceEnforcing custom enumeration in AWS LEX for slot valuesHow to give response based on user response in Amazon Lex?Intercepting AWS Lambda Response to a AWS Lex QueryLex chat bot error: Reached second execution of fulfillment lambda on the same utteranceamazon lex showing invalid responseLambda response send back to Lex slot?Response card in Amazon lexAmazon Lex - Lambda response return HTML to botHow can I solve 424 (Failed Dependency) (python) obtained from Amazon lex?

Алба-Юлія

Захаров Федір Захарович