logo
down
shadow

how to create instance for a generic type in c#


how to create instance for a generic type in c#

By : user3855084
Date : January 02 2021, 06:48 AM
should help you out I need to create an parameterless instance for a Generic Class in C#. , You could add the : new() constraint:
code :


Share : facebook icon twitter icon
Create an instance of a class from an instance of the type of its generic parameter

Create an instance of a class from an instance of the type of its generic parameter


By : NeonVibe
Date : March 29 2020, 07:55 AM
I hope this helps . I want to do this: , You can use a custom implicit operator, e.g:
code :
public static implicit operator ValueContainer<T>(T value) {
    return new ValueContainer { Value = value };
}
Is it possible create a new instance of a generic type inside the body of a generic method?

Is it possible create a new instance of a generic type inside the body of a generic method?


By : user2098770
Date : March 29 2020, 07:55 AM
around this issue You can have your generic type implement an interface. Then place restrictions in your generic method to only accept types that implement that interface. This will allow you to call methods on your newly constructed item as it's known to have those methods.
code :
public interface ITest
{
    void DoSomething();
}

public void GetData<T, U>(T varA, int acao) where U: ITest, new()
{
    var item = new U();
    item.DoSomething();
} 
Create instance of class with generic type and call method of same generic type from string name of object at runtime

Create instance of class with generic type and call method of same generic type from string name of object at runtime


By : lukawanjohi
Date : March 29 2020, 07:55 AM
Hope this helps I have a generic class that has a generic method that uses the same type as the type passed when instantiating the object. At runtime, I will only know the name of the object I need to pass in by a string representation of that object name. I've read a few things about using Activator and possibly using dynamic but I can't wrap my head around how I need to make this work. Here's a snippet of what my generic class looks like: , Your wrapper got the following signature:
code :
public class MyClass<T> where T : class, new()
var obj = new T();
public class MyClass<T> where T : class, new()
{ 
        public IList<T> MyMethod(Stream stream)
        {
             var data = new List<T>();

             //this
             var obj = new T();

             return data;
        }
}
var obj = new T();

//get type information
var type = obj.GetType();

//find a public method named "DoStuff"
var method = type.GetMethod("DoStuff");

// It got one argument which is a string.
// .. so invoke instance **obj** with a string argument
method.Invoke(obj, new object[]{"a string argument"});
var type = Type.GetType("Some.Namespace.ClassName");
var obj = Activator.CreateInstance(type);
var type = Type.GetType("Some.Namespace.ClassName, SomeAsseblyName");
var obj = Activator.CreateInstance(type);
var type = Assembly.GetExecutingAssembly()
                   .GetTypes()
                   .FirstOrDefault(x => x.Name == "YourName");
var obj = Activator.CreateInstance(type);
Create instance of a generic type that takes a parameter a secondary generic type

Create instance of a generic type that takes a parameter a secondary generic type


By : Saul CI
Date : March 29 2020, 07:55 AM
will be helpful for those in need After Abion47 pointed out that Activator.CreateInstance shouldn't have any issues doing what I need it to do I looked a bit more into the issue and made it work.
For anyone that might come across this:
code :
public abstract class Sentinel<T,U> where T: new() where U: new() 
{
    public T CreateModel(IDictionary<String, Object> parametersDictionary)
    {
        T toReturn ;

        if (ValidateDictionary(parametersDictionary) != true)
            return default(T);
        else
        {
            U parameters = ParseDictionaryToParameters(parametersDictionary);
            toReturn = (T)Activator.CreateInstance(typeof(T), new object[] {parameters});
        }

        //If we got this far then everything should be fine.
        return toReturn;
    }

    public abstract U ParseDictionaryToParameters(IDictionary<String, Object> parametersDictionary);

    public abstract Boolean ValidateDictionary(IDictionary<String, Object> parametersDictionary);
}
Create instance of generic class with dynamic generic type parameter

Create instance of generic class with dynamic generic type parameter


By : Lisa Jack
Date : March 29 2020, 07:55 AM
wish of those help I found very simple solution to problem. There is no need to cast object to specific type T, just use dynamic keyword instead of casting
code :
   Type myGeneric = typeof(MyComparer<>);
   Type constructedClass = myGeneric.MakeGenericType(T);
   object created = Activator.CreateInstance(constructedClass);
   dynamic comparer = created; // No need to cast created object to T
   return comparer.Equals(myResultAsT, correctResultAsT);
Related Posts Related Posts :
  • Looking for a .Net ORM
  • Cost of SortedDictionary.Count
  • All possible combinations of n items selected randomly from a set of x items (algorithm)
  • Displaying process percentage on DOS screen
  • C# Importing Large Volume of Data from CSV to Database
  • c# control location precision
  • Printing to Zebra printer gives faint and blurry images
  • How to avoid stepping into dll code file?
  • Programmaticaly prevent Vista desktop search (WDS) from indexing pst files placed on mapped network drives
  • Is there anyway to reduce IsolatedStorage capacity in Silverlight?
  • C#: How to print a unicode string to console?
  • Frequency Table with Random Values
  • My Visual Studio 2008 web application keeps throwing a .Net error when I first run it, but refreshing fixes it
  • TCP Connection Creation and Closing Event Hooking
  • Find changed properties of a class
  • C#: Object with custom marshaller not containing data after PInvoke call
  • Version Control System with API. Need to get metrics
  • Performance comparison of Dictionaries
  • How to get process name and title of the top window on Windows / C#
  • How to save the ListView contents to a text file?
  • Why not .NET-style delegates rather than closures in Java?
  • Get CLSID by PIA interface Type
  • Visual Studio 2008 C# - Recover solution from application manifest possible?
  • Is a good practice to initialize private data members from within ctor by calling the associated properties instead of t
  • Inserting into a bitstream
  • How do you write byte[] array using log4.net
  • Clickonce + .NET client profile 4 framework + offline
  • Show form that showDialog from mainForm won't block it, but closing mainForm will close it
  • Developing a GPS car tracking system
  • dynamic log4net appender name?
  • Visual studio formatting issue
  • IndexOutOfRangeException when a stream is a multiple of the buffer size
  • How to deal with calculated values with Dependency Properties on a custom WPF control
  • counting from textbox,asp.net
  • Threading best practice when using SFTP in C#
  • how to load PDF file in website page using C#
  • Parent child class relationship design pattern
  • MessageQueue.BeginReceive() null ref error - c#
  • A C# collection, which behaves like C++ set or priority_queue?
  • Animating WPF buttons from inside a style
  • WPF Grid : GridSplitter event
  • Server 2008 Task Scheduler Mapped Drive Access C#
  • Cast problem with LINQ
  • Combo box Item source = ObservableCollection & I need a '-None-' dummy entry at the top
  • Which GUI control is suitable for this purpose?
  • Trying to access App.config file for mail settings but fails to work
  • Invoke PowerShell script from c# in runspace and get line number where error occured
  • How to show html contents with a RichTextBox?
  • FTP monitoring and downloading of new files
  • MEF + Plug-In not updating
  • Efficient handling of super wide, but not so tall, bitmap?
  • .NET 3.0 Unit Testing getting System.MethodAccessException calling .NET 2.0
  • Web Services vs Persistent Sockets
  • How do I dynamically reference incremented properties in C#?
  • Windows Installer (C#) error code 2869
  • Exception "The operation is not valid for the state of the transaction" using TransactionScope
  • Tools for listing database accesses from .NET code
  • Excel VSTO set selection
  • Creating a subscription based website in ASP.NET
  • Merging Resources Dictionaries
  • shadow
    Privacy Policy - Terms - Contact Us © 35dp-dentalpractice.co.uk