Tags down


How to create a new object instance from a Type

By : Matt
Date : March 29 2020, 07:55 AM
help you fix your problem The Activator class within the root System namespace is pretty powerful.
There are a lot of overloads for passing parameters to the constructor and such. Check out the documentation at:
code :
ObjectType instance = (ObjectType)Activator.CreateInstance(objectType);

ObjectType instance = (ObjectType)Activator.CreateInstance("MyAssembly","MyNamespace.ObjectType");

Share : facebook icon twitter icon

Create an instance of an unknown type of object and TryUpdateModel

By : Alex Lombry
Date : March 29 2020, 07:55 AM
This might help you I'm using MVC and i have a controller action which handles several different view models, each view model has validation and i'd like the controller to check the validation. , You will need to write a custom model binder for this to work:
code :
public class MyModelBinder : DefaultModelBinder
    protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType)
        var typeValue = bindingContext.ValueProvider.GetValue("viewType");
        var type = Type.GetType(
        var model = Activator.CreateInstance(type);
        bindingContext.ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => model, type);
        return model;
public ActionResult WizardCaseResult([ModelBinder(typeof(MyModelBinder))]object model)
ViewType vm = new ViewType();

Create instance with type object during runtime

By : Obi Osonduagwueki
Date : March 29 2020, 07:55 AM
like below fixes the issue First step is to retrieve the actual type you want to create. Most probably, the name of the type is stored in the database as a String. So you call
code :
var typeName = "System.Int32";
var type = System.Type.GetType(typeName);
var obj = System.Activator.CreateInstance(type);
var i = (IFormattable)obj;
Console.WriteLine(i.ToString("0", System.Globalization.CultureInfo.InvariantCulture));

How to create a new instance of a object type

By : user2295992
Date : March 29 2020, 07:55 AM
will help you I have a base class where I inherit my forms. , You don't need to cast it as anything; object is fine:
code :
object instance = Activator.CreateInstance(type);

Using the class type of an object to create a new instance

By : Robert Martinez Mart
Date : March 29 2020, 07:55 AM
like below fixes the issue To realise the line Clazz user = (Clazz) o;, in the save method, where Clazz is the class of the object passed to the save method, so in this case User, you can make use of generics in the signature of save as follows:
code :
public <T> void save(T user) throws IllegalAccessException, InstantiationException, InvocationTargetException {
    int i = 0;
    List<Object> args = new ArrayList<>();
    T newUser = (T)user.getClass().getConstructors()[i].newInstance(args);
    // Exciting things...

Determine a object's type based on a string and create a new instance?

By : Kanishka Dilshan
Date : March 29 2020, 07:55 AM
To fix this issue You can scan current assembly (or whatever assembly that contains your shapes) for types that inherited from Shape, and use Activator.CreateInstance to create the instance. It's better if you cache the name and type in a dictionary, so you can quickly lookup the type that you want.
code :
var type_str = "Circle";

// TypeChache should be static field
if (TypeChache == null)
    var assem = Assembly.GetExecutingAssembly();
    TypeChache = assem.GetTypes()
                 .Where(x => typeof(Shape).IsAssignableFrom(x))
                 .ToDictionary(x=>x.Name, x=>x);

var type = TypeChache[type_str];    
var inst = (Shape) Activator.CreateInstance(type);
Related Posts Related Posts :
  • How to check whether string contains specific string in c#
  • UPnP hole punching can't use external IP to access device on local subnet
  • Is there a way to use a conditional when declaring method variables?
  • c# interop Excel - disable or remove automatic page breaks
  • How can I read in these commands from a file using?
  • Pinch and rotate around a point using MRTK and Hololens 1
  • Enhance performance to paint image, is SIMD perhapse a solution?
  • Which one has better performance, data types .NET or alias name data types C#?
  • HttpClient GetAsync taking ~2 seconds
  • linq fastest where method
  • Why can I read more than 254 characters with Console.ReadLine when the docs suggest that I shouldn't be able to?
  • C# - Delayed execution for a collection of items
  • How to display images in a CollectionView from a Base64 string?
  • Convert class object to class index
  • c# identifier expected in controller
  • Subscribe to multiple Observables and gets notified on the same thread
  • how to create windows service using crud operations in c# asp.net
  • Iterating through list of values in a dictionary c#
  • How to Implement Expo.io Push Notifications Send Through C#
  • Gridview columns not being set to width I enter
  • Impersonate User with Forms Authorization
  • ASP.NET MVC Impersonate not working with Forms Authentication
  • Found a potential bug in Moq library while selecting a constructor
  • I want to show a list but page is empty
  • Can this kind of concurrency problem be solved with async/await?
  • Yield keyword giving unexpected values for IEnumerable
  • Many DLLs in System namespace are included when installing library via Nuget
  • C# - range for textbox inputs
  • the Console.ReadLine() Doesn't set the string as the user input
  • Get notified when a variable changed
  • How to list players in room in Photon?
  • Link compile-time created resources to a class library
  • How to quickly choose numbers and weights in such a way as to obtain a specific weighted sum?
  • Downgrade .Net Core project from 3.1 to 2.2 - The type or namespace name 'IWebHostEnvironment' could not be found
  • c# multiplying array elements using system.numerics
  • Private methods vs local functions
  • C# project wants .NET 4.7.1 but I can't install it
  • Binding to object itself, doesn't update when individual property changes
  • remove duplicate from list in object c#
  • JSON.NET - find JObject by value regex in complex object?
  • Save an unknown sized array from unknown string length
  • Camera not centre on player sprite (monogame)
  • How to set a default type for T in a static generic method?
  • How can I insert multiple items of data into SQL using Web API?
  • Finding longest time in an array
  • How to find two quotation marks in a string
  • X509Certificate2 certification issue
  • Image format change in Azure
  • Why is there such big time difference in searching for element with higher index in ConcurrentBag?
  • Async Lambda Issue
  • C# SSIS Script Task - Add Thousand Seperator when formatting Excel column
  • How to check if a textbox starts with numeric value
  • c# Strange Pairs || I can't spot the difference between these 2 solutions?
  • str.Split(".") not working in C# interactive window but work in C# .Net core project?
  • How to do 3 conditions with if else C#
  • merge two lists of same type in c#
  • Blazor - SortBy parameter for table column component
  • InvalidCastException: Specified cast is not valid Error when tried to fetch image from url
  • Search based on Properties
  • Ref string parameter is empty?
  • shadow
    Privacy Policy - Terms - Contact Us © voile276.org