Create Generic object inside class [duplicate] - c#

This question already has answers here:
Passing arguments to C# generic new() of templated type
(16 answers)
Closed 9 years ago.
I am making a base class from which other classes can be derived.
public class BaseClass<T> where T
{
public BaseClass()
{
TClassObject = new T("SomeText"); // Error here
}
public T TClassObject { get; set; }
}
'T': cannot provide arguments when creating an instance of a variable type.
What I am missing here.

From MSDN:
The new constraint specifies that any type argument in a generic class declaration must have a public parameterless constructor.
So it needs to be parameterless. You may want to look at Activator.CreateInstance
http://msdn.microsoft.com/en-us/library/system.activator.createinstance.aspx

The where T : new() constraint states that T must have a parameterless constructor. Your code is calling into a constructor that takes a string parameter, and it isn't guaranteed that your T will have such a constructor.
It is not possible in C# to create a constraint on a specific constructor signature. If you need this functionality, you're better off using something like one of the answers in this thread.

Related

c# base key word outside constructor [duplicate]

This question already has answers here:
Calling the base constructor in C#
(10 answers)
Closed 7 years ago.
namespace ClientApp
{
[Service(Exported = false)]
class RegistrationIntentService : IntentService
{
static object locker = new object();
public RegistrationIntentService() : base("RegistrationIntentService") { }
In the snippet above, the constructor extends a base("RegistrationIntentService"), what is this doing?
I found this example at:
https://developer.xamarin.com/guides/cross-platform/application_fundamentals/notifications/android/remote_notifications_in_android/
Does it mean the contructor is the same as the RegistrationIntentService constructor?
This is just calling IntentService's constructor with a string parameter "RegistrationIntentService". It is a C# language keyword and is not Xamarin specific.
If the base class of an object does not have a default constructor, you must provide parameters to a base constructor in the derived class's constructor using this syntax.
See the MSDN documentation on the base keyword for some examples.

Pass type of current class/object to a generic method without explicit type reference in C# program? [duplicate]

This question already has answers here:
Generic class from type parameter
(2 answers)
Closed 10 years ago.
Is there a short hand for the type of the current class/object that I can use when calling a generic method, instead of having to explicitly pass the name of the current class/object?
For example, given the sample code below:
public class SomeClass
{
public SomeClass()
{
// Call some generic method that returns a string.
string s = GenMeth<SomeClass>)();
}
} // public class SomeClass
Is there a way to tell C# that I want to pass the class of the current class (SomeClass) to GenMeth() without having to explicitly say SomeClass?
A hypothetical and bogus example that illustrates the concept:
string s = GenMeth<GetType(this)>();
If you make your method consume an instance of that type, it can infer it. For example, if your method looked like:
void GenMeth<T>(T instance) {}
Then you could invoke it like:
GenMeth(this);
Whether this would be acceptable to you might be a different story. (it would be a bit weird if you never consumed the argument)
No, there is no such syntax.
You could, in theory, call the method via reflection, thus allowing you to use this.GetType(), but that would make things much, much worse for you. Just...don't do that. It's much easier to just remember to change the generic argument to the current type if you copy/paste the code.
You can create an extension method that performs whatever your operation is on any object. You can check in the extension method for types that are legitimate using GetType().
public static class ObjectExtensions {
public static string GenMeth(this object obj) {
// do stuff here and return string type
}
}

Class syntax with <TypeParameter> C# [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What does “T” mean in C#?
What does <T> denote in C#
I have searched about the question, but because I do not have any idea about that syntax, I could not search well enough. Well, after the short explanation my question is :
While I was looking to a particle effect library I meet this :
[Serializable]
public class DPSF<Particle, Vertex> : IDPSFParticleSystem
where Particle : global::DPSF.DPSFParticle, new()
where Vertex : struct, global::DPSF.IDPSFParticleVertex
{
// constructors, methods, parameters here ...
}
What does this notation mean in blankets (<...>) and how it is used ?
They are generic types that you can pass into a class definition:
A simple example:
public class Test<T>
{
public T yourVariable;
}
Test<int> intClass = new Test();
Test<string> stringClass = new Test();
intClass.yourVariable // would be of type int
stringClass.yourVariable // would be of type string
Where T is the type you want (i.e. another class, a string, integer, anything generic)
where Particle : global::DPSF.DPSFParticle - means that the Particle object must inherit from DPSF.DPSFParticle
It means that DPSF class is a generic class. Particle and Vertex between <> are type parameters. It means that DPSF gets two types as parameters and serves as a generic class.
Take a look at here: MSDN: Generics
EDIT
Where keyword allows you to restrict type parameters. where:class means parameter must be a class in order this generic class to work.

How do I create an instance from a string that provides the class name? [duplicate]

This question already has answers here:
Create an instance of a class from a string
(8 answers)
Closed 9 years ago.
I have to write a function with class Name as Parameter to function, which is in string. So that i need to create instance of this class name.
createInstance(string ClassName){
.............
//Here i Need to create instance of ClassName,
.............
}
Activator.CreateInstance(Type.GetType(ClassName));
Type t = Assembly.GetType(className);
Activator.CreateInstance(t);
Works only if T is a public type and has a parameterless, public constructor. But thats the pattern and it can be made to work in other cases too.
As everybody told you, you have to get the type you are looking for and then pass it to the CreateInstance method of Activator in this way:
Type t = Type.GetType(className);
Activator.CreateInstance(t);
Just be careful to the fact that if you pass to GetType the fullname of the class you are trying to instantiate (e.g. "MyNamespace.Foo"), it returns you the type only if it is called from inside the same assembly as the searched class, otherwise it returns null.
If you want to have it work for types that are in a generic assembly you have to use the AssemblyQualifiedName (take a look here for the details: http://msdn.microsoft.com/en-us/library/system.type.assemblyqualifiedname.aspx)

C# where keyword [duplicate]

This question already has answers here:
What does the keyword "where" in a class declaration do?
(7 answers)
Closed 9 years ago.
In the following piece of code (C# 2.0):
public abstract class ObjectMapperBase< T > where T : new()
{
internal abstract bool UpdateObject( T plainObjectOrginal,
T plainObjectNew,
WebMethod fwm,
IDbTransaction transaction );
}
Inheritor example:
public abstract class OracleObjectMapperBase< T > : ObjectMapperBase< T > where T : new()
{
internal override bool UpdateObject( T plainObjectOrginal,
T plainObjectNew,
WebMethod fwm,
IDbTransaction transaction )
{
// Fancy Reflection code.
}
}
What does the where keyword do?
it is a constraint for generics
MSDN
so the new() constraint says it must have a public parameterless constructor
It specifies a constraint on the generic type parameter T.
The new() constraint specifies that T must have a public default constructor.
You can also stipulate that the type must be a class (or conversely, a struct), that it must implement a given interface, or that it must derive from a particular class.
The where clause is used to specify constraints on the types that can be used as arguments for a type parameter defined in a generic declaration. For example, you can declare a generic class, MyGenericClass, such that the type parameter T implements the IComparable interface:
public class MyGenericClass<T> where T:IComparable { }
In this particular case it says that T must implement a default constructor.
This is a generic type constraint. It means that the generic type T must implement a zero parameter constructor.
The Where keyword is basically a constraint on the objects the class can work on/with.
taken from MSDN "The new() Constraint lets the compiler know that any type argument supplied must have an accessible parameterless constructor"
http://msdn.microsoft.com/en-us/library/6b0scde8(VS.80).aspx
It means the T has to have a public default constructor.

Categories