Ali Yousefi
Ali Yousefi

Reputation: 2743

how to return T type from static method in C#?

I want to use static member in my class and I don't want to use <T> from my static method.

public class Person : AQuaryTable
{
    public string Name { get; set; }
}
public class User : AQuaryTable
{
    public string UserName { get; set; }
}
public class AQuaryTable
{
    public static List<T> SelectAll<T>()//static this T tmp
    {
        var getType = typeof(T);
        return null;
    }
}

use this:

var listOfPersons1 = Person.SelectAll<Person>();//don't want use type <Person>
var listOfUsers1 = User.SelectAll<User>();//don't want use type <User>

//I want to use this code:
var listOfPersons = Person.SelectAll();//exception 
var listOfUsers = User.SelectAll();//exception 

Upvotes: 1

Views: 162

Answers (3)

Xharlie
Xharlie

Reputation: 2540

Fundamentally, designing a pattern that relies on inheritance of static methods is not a good idea but, if you must, you could try this idea:

public class Person : QueryTable<Person>
{
    public string Name { get; set; }
}

public class User : QueryTable<User>
{
    public string UserName { get; set; }
}

public abstract class QueryTable
{
    // TODO: Write as much as you can, here.

    protected static List<T> SelectAll<T>()
    {
        // ...
    }
}

public abstract class QueryTable<T> : QueryTable
{
    public static List<T> SelectAll()
    {
        return QueryTable.SelectAll<T>();

        // Note: You could just implement this inline, here.
    }

    // TODO: Put stuff that is specific to T, here.
}

Upvotes: 0

CodeCaster
CodeCaster

Reputation: 151604

Make it an instance method and make the base class generic:

public class AQuaryTable<T>
{
    public List<T> SelectAll()
    {
    }
}

public class User : AQuaryTable<User>
{

}

Upvotes: 0

Selman Gen&#231;
Selman Gen&#231;

Reputation: 101701

You can make SelectAll an extension method

public static List<T> SelectAll<T>(this T source) where T : AQuaryTable

Then you should be able to call it like this:

var listOfPersons = Person.SelectAll();

Note: You need to declare SelectAll method in a static class.

Upvotes: 3

Related Questions