C# generics: How to pass current class's type as a para

generic class c#
c# instantiate generic type
c# typeof generic
c# create instance of generic type at runtime
c# generic method
c# reflection generic type
create instance of generic type c#
c# generic constructor

I would like to

  1. Move my OnModelCreating to the base class and
  2. Call modelBuilder.Entity<T> without explicitly specifying the T. I would just like to say, the 'current class' (meaning in this example UserType as it is UserType on which the index needs creating)
public class BaseLookupEntity : BaseEntity
{
    [Key()]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public override int Id { get; set; }

    //...

}

public class UserType: BaseLookupEntity
{
    internal static void OnModelCreating(ModelBuilder modelBuilder)
    {
        // unique 
        modelBuilder.Entity<UserType>()
            .HasIndex(c => c.Enum)
            .IsUnique();
    }

}

You would want to make your base class generic as well in that case

public class BaseLookupEntity<T> : BaseEntity where T : BaseLookupEntity<T>
{
    [Key()]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public override int Id { get; set; }

    internal static void OnModelCreating(ModelBuilder modelBuilder)
    {
        // unique 
        modelBuilder.Entity<T>()
            .HasIndex(c => c.Enum)
            .IsUnique();
    }
}

public class UserType: BaseLookupEntity<UserType>
{
}

How to: Examine and Instantiate Generic Types with Reflection , In the following code, the type is obtained using the C# typeof operator ( GetType in Visual Basic, typeid in Visual C++). See the Type class topic� Generics introduced in C# 2.0. It allows you to define a class with placeholders for the type of its fields, methods, parameters, etc. Generics replace these placeholders with some specific type at compile time. A generic class can be defined using angle brackets <>. For example, the following is a simple generic class with a generic member

Using generics, you can't.

Generics are evaluated at compile time, but as your base class will have multiple sub classes, the type will only be known at runtime.

There is an overload for ModelBuilder.Enity that accepts a System.Type object, which can be used at runtime, so you could use that in your base class.

Personally i would do this in your DbContext and list all the base classes individually e.g.

private void MapLookupEntitity<TLookup>(DbModelBuilder modelBuilder) where TLookup : BaseLookupEntity
{
    // unique 
    modelBuilder.Entity<TLookup>()
        .HasIndex(c => c.Enum)
        .IsUnique();
}

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    MapLookupEntitity<UserType>(modelBuilder);
    MapLookupEntitity<AnotherType>(modelBuilder);
    // map some more..
}

Type.MakeGenericType(Type[]) Method (System), The current type does not represent a generic type definition. C# Copy. using System; using System.Reflection; using System.Collections. Create a type object representing the generic Dictionary // type, by omitting the type arguments (but� 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.

There is in-built support for decoupled (from DB context) configurations. Your configuration class must implement IEntityTypeConfiguration<T> interface.

Then you can easily apply configurations inside your DbContext's OnModelCreating method using ApplyConfiguration<T> method.

Your example, could look like:

public class CustomDbContext : DbContext
{
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.ApplyConfiguration<UserTypeConfiguration>(new UserTypeConfiguration());
    }
}

public class UserTypeConfiguration : IEntityTypeConfiguration<UserType>
{
    public void Configure(EntityTypeBuilder<UserType> builder)
    {
        builder
            .HasIndex(c => c.Enum)
            .IsUnique();
    }
}

Note: I can't try your inheritance chain, but it should work out of the box, if you do:

Generic Interfaces, The preference for generic classes is to use generic interfaces, such as protected Node current = null; // Nested class is also generic on T� Generics allow you to define the specification of the data type of programming elements in a class or a method, until it is actually used in the program. In other words, generics allow you to write a class or method that can work with any data type. You write the specifications for the class or the method, with substitute parameters for data types.

class someBaseClass
{
    public void Foo<TInferrConcreteDerivedTypeCallingThisMethodHere>()
}

No, thats not possible, and if you understand how generics works you'd see why. Generic types are not resolved at runtime (excluding dynamic and reflection scenarios), all generic type parameters are resolved at compile time. Therefore, there is no way the compiler can know what the real type of TInferrConcreteDerivedTypeCallingThisMethodHere is from within SomeBaseClass without running the code.

Inheritance is a red herring here, the same issue arises with the classical example of statically unknown types:

void Foo<T>(T t) { ... }

object o = GetSomeRuntimeObjectIDontKnowTheTypeOf();
Foo(o); T is inferred

Can you guess what T is inferred to? You can narrow it down to two options: Foo<RuntimeTypeOfUnkownObject> or Foo<object>? If you have doubts, run it and figure it out.

Also, as far as type inference goes, a rule of the thumb, whenever you have a generic method with a signature similar to:

void Foo<T>(/*no arguments from which T can be inferred*/)

or even

T Foo<T>(/*no arguments from which T can be inferred*/)

T can not or will not be inferred.

Generic Types (The Java™ Tutorials > Learning the Java Language , A generic type is a generic class or interface that is parameterized over types. Since its methods accept or return an Object, you are free to pass in whatever� Generics (C# Programming Guide) 07/20/2015; 3 minutes to read +8; In this article. Generics introduce the concept of type parameters to .NET, which make it possible to design classes and methods that defer the specification of one or more types until the class or method is declared and instantiated by client code.

Generic Parameter Constraints for C#, Generic became part of C# with version 2.0 of the language and the A generic class cannot be used as-is because it is simply a blueprint for We know when generics were born and what type of constraints are present on� Beginning in C# 7.3, you can also specify the System.Enum type as a base class constraint. The CLR always allowed this constraint, but the C# language disallowed it. Generics using System.Enum provide type-safe programming to cache results from using the static methods in System.Enum. The following sample finds all the valid values for an enum

Generics in C#, (a) Explicitly, by requiring that the client of the class pass extra parameters to the Implementation note: Currently only one constraint is allowed per generic� Generic Interfaces (C# Programming Guide) 07/20/2015; 4 minutes to read +4; In this article. It is often useful to define interfaces either for generic collection classes, or for the generic classes that represent items in the collection.

Generics � TypeScript, In languages like C# and Java, one of the main tools in the toolbox for creating The first way is to pass all of the arguments, including the type argument, to the function: Generic classes have a generic type parameter list in angle brackets� I think you need to qualify the generic T better, otherwise you could pass in a double, string, int, object into the constructor and it would not work as expected. – Moop Mar 3 '13 at 23:49 Yes, that would be a very good idea.

Comments
  • That's just pushing the problem a step up. He'll still have to explicitly say what T is, which is what he seems to want to avoid. Not saying its possible though... this seems an XY problem unless he just wants to avoid typing the few extra keystrokes.
  • @InBetween I've possibly misconstrued the problem, I thought the OP was just looking to move the code into somewhere common so they don't have to keep overriding OnModelCreating when deriving new types.