Creating a generic method in C# through specific where clause

Multi tool use
I want to create some generic methods like code below:
public async Task<T> Get<T>(string url) where T : IBaseModel, IList<IBaseModel>
Obviously I want to support enumerable collection and also the single object which drived from IBaseModel
interface.
The method definition is OK, but when it comes to its usage I'll get following error:
await myClass.Get<List<DrivedClassFromBaseModel>>("some url");
There is no implicit conversion from "System.Collection.Generic.List<DrivedClassFromBaseModel> to System.Collection.Generic.IList<IBaseModel>"
c# .net generics
add a comment |
I want to create some generic methods like code below:
public async Task<T> Get<T>(string url) where T : IBaseModel, IList<IBaseModel>
Obviously I want to support enumerable collection and also the single object which drived from IBaseModel
interface.
The method definition is OK, but when it comes to its usage I'll get following error:
await myClass.Get<List<DrivedClassFromBaseModel>>("some url");
There is no implicit conversion from "System.Collection.Generic.List<DrivedClassFromBaseModel> to System.Collection.Generic.IList<IBaseModel>"
c# .net generics
2
You cannot cast a list of a derived type to a list with the base class. That would allow for other types with the same base class to be added to that list.
– Biesi Grr
Dec 30 '18 at 12:38
1
HowList<DrivedClassFromBaseModel>
could beIBaseModel
?
– Reza Aghaei
Dec 30 '18 at 12:40
You should be able to do Task<List<T>> Get<T>(string url) where T : IBaseModel
– stannius
Dec 30 '18 at 12:58
@Reza Aghaei DrivedClassFromBaseModel:IBaseModel
– Saman Gholami
Dec 30 '18 at 14:42
1
I see, butDrivedClassFromBaseModel:IBaseModel
doesn't meanList<DrivedClassFromBaseModel>
isIBaseModel
. As it's already mentioned in the answer,where T : IBaseModel, IList<IBaseModel>
meansT
should implement bothIBaseModel
andIList<IBaseModel>
.
– Reza Aghaei
Dec 30 '18 at 18:57
add a comment |
I want to create some generic methods like code below:
public async Task<T> Get<T>(string url) where T : IBaseModel, IList<IBaseModel>
Obviously I want to support enumerable collection and also the single object which drived from IBaseModel
interface.
The method definition is OK, but when it comes to its usage I'll get following error:
await myClass.Get<List<DrivedClassFromBaseModel>>("some url");
There is no implicit conversion from "System.Collection.Generic.List<DrivedClassFromBaseModel> to System.Collection.Generic.IList<IBaseModel>"
c# .net generics
I want to create some generic methods like code below:
public async Task<T> Get<T>(string url) where T : IBaseModel, IList<IBaseModel>
Obviously I want to support enumerable collection and also the single object which drived from IBaseModel
interface.
The method definition is OK, but when it comes to its usage I'll get following error:
await myClass.Get<List<DrivedClassFromBaseModel>>("some url");
There is no implicit conversion from "System.Collection.Generic.List<DrivedClassFromBaseModel> to System.Collection.Generic.IList<IBaseModel>"
c# .net generics
c# .net generics
edited Dec 30 '18 at 13:58
Reza Aghaei
65.8k854162
65.8k854162
asked Dec 30 '18 at 12:19


Saman GholamiSaman Gholami
1,88952154
1,88952154
2
You cannot cast a list of a derived type to a list with the base class. That would allow for other types with the same base class to be added to that list.
– Biesi Grr
Dec 30 '18 at 12:38
1
HowList<DrivedClassFromBaseModel>
could beIBaseModel
?
– Reza Aghaei
Dec 30 '18 at 12:40
You should be able to do Task<List<T>> Get<T>(string url) where T : IBaseModel
– stannius
Dec 30 '18 at 12:58
@Reza Aghaei DrivedClassFromBaseModel:IBaseModel
– Saman Gholami
Dec 30 '18 at 14:42
1
I see, butDrivedClassFromBaseModel:IBaseModel
doesn't meanList<DrivedClassFromBaseModel>
isIBaseModel
. As it's already mentioned in the answer,where T : IBaseModel, IList<IBaseModel>
meansT
should implement bothIBaseModel
andIList<IBaseModel>
.
– Reza Aghaei
Dec 30 '18 at 18:57
add a comment |
2
You cannot cast a list of a derived type to a list with the base class. That would allow for other types with the same base class to be added to that list.
– Biesi Grr
Dec 30 '18 at 12:38
1
HowList<DrivedClassFromBaseModel>
could beIBaseModel
?
– Reza Aghaei
Dec 30 '18 at 12:40
You should be able to do Task<List<T>> Get<T>(string url) where T : IBaseModel
– stannius
Dec 30 '18 at 12:58
@Reza Aghaei DrivedClassFromBaseModel:IBaseModel
– Saman Gholami
Dec 30 '18 at 14:42
1
I see, butDrivedClassFromBaseModel:IBaseModel
doesn't meanList<DrivedClassFromBaseModel>
isIBaseModel
. As it's already mentioned in the answer,where T : IBaseModel, IList<IBaseModel>
meansT
should implement bothIBaseModel
andIList<IBaseModel>
.
– Reza Aghaei
Dec 30 '18 at 18:57
2
2
You cannot cast a list of a derived type to a list with the base class. That would allow for other types with the same base class to be added to that list.
– Biesi Grr
Dec 30 '18 at 12:38
You cannot cast a list of a derived type to a list with the base class. That would allow for other types with the same base class to be added to that list.
– Biesi Grr
Dec 30 '18 at 12:38
1
1
How
List<DrivedClassFromBaseModel>
could be IBaseModel
?– Reza Aghaei
Dec 30 '18 at 12:40
How
List<DrivedClassFromBaseModel>
could be IBaseModel
?– Reza Aghaei
Dec 30 '18 at 12:40
You should be able to do Task<List<T>> Get<T>(string url) where T : IBaseModel
– stannius
Dec 30 '18 at 12:58
You should be able to do Task<List<T>> Get<T>(string url) where T : IBaseModel
– stannius
Dec 30 '18 at 12:58
@Reza Aghaei DrivedClassFromBaseModel:IBaseModel
– Saman Gholami
Dec 30 '18 at 14:42
@Reza Aghaei DrivedClassFromBaseModel:IBaseModel
– Saman Gholami
Dec 30 '18 at 14:42
1
1
I see, but
DrivedClassFromBaseModel:IBaseModel
doesn't mean List<DrivedClassFromBaseModel>
is IBaseModel
. As it's already mentioned in the answer, where T : IBaseModel, IList<IBaseModel>
means T
should implement both IBaseModel
and IList<IBaseModel>
.– Reza Aghaei
Dec 30 '18 at 18:57
I see, but
DrivedClassFromBaseModel:IBaseModel
doesn't mean List<DrivedClassFromBaseModel>
is IBaseModel
. As it's already mentioned in the answer, where T : IBaseModel, IList<IBaseModel>
means T
should implement both IBaseModel
and IList<IBaseModel>
.– Reza Aghaei
Dec 30 '18 at 18:57
add a comment |
2 Answers
2
active
oldest
votes
Generic constraints will be combined by AND, so where T : IBaseModel, IList<IBaseModel>
means T
should implement both IBaseModel
and IList<IBaseModel>
.
You need to create two methods:
public async Task<T> Get<T>(string url) where T : IBaseModel
public async Task<IList<T>> GetList<T>(string url) where T : IBaseModel
If these two methods are member of the same class which can have<T>
as common generic constraint, moveT
to generic parameters of the class.
– Reza Aghaei
Dec 30 '18 at 13:22
add a comment |
You can use another class which implements both IBaseModel and IList, and then T is constrained to this class.
public class DerivedModel : IBaseModel, IList<IBaseModel>
{
private int _size;
private IBaseModel _items=new IBaseModel[1000];
private int _version;
public int Id { get; set; }
public IEnumerator<IBaseModel> GetEnumerator()
{
throw new NotImplementedException();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
...
}
And the generic method is:
public async Task<T> Get<T>(string url) where T : DerivedModel
{
return await Task<T>.Factory.StartNew(() =>
{
var derivedModel = new DerivedModel() {new BaseModel() {Id = 1}};
return (T) derivedModel;
});
}
In which the IBaseModel and BaseModel can be:
public interface IBaseModel
{
int Id { get; set; }
}
public class BaseModel : IBaseModel
{
public int Id { get; set; }
}
The usage:
var inheritance=new Inheritance();
var result = await inheritance.Get<DerivedModel>("aaa");
textBox1.Text = result[0].Id.ToString();
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53977528%2fcreating-a-generic-method-in-c-sharp-through-specific-where-clause%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
Generic constraints will be combined by AND, so where T : IBaseModel, IList<IBaseModel>
means T
should implement both IBaseModel
and IList<IBaseModel>
.
You need to create two methods:
public async Task<T> Get<T>(string url) where T : IBaseModel
public async Task<IList<T>> GetList<T>(string url) where T : IBaseModel
If these two methods are member of the same class which can have<T>
as common generic constraint, moveT
to generic parameters of the class.
– Reza Aghaei
Dec 30 '18 at 13:22
add a comment |
Generic constraints will be combined by AND, so where T : IBaseModel, IList<IBaseModel>
means T
should implement both IBaseModel
and IList<IBaseModel>
.
You need to create two methods:
public async Task<T> Get<T>(string url) where T : IBaseModel
public async Task<IList<T>> GetList<T>(string url) where T : IBaseModel
If these two methods are member of the same class which can have<T>
as common generic constraint, moveT
to generic parameters of the class.
– Reza Aghaei
Dec 30 '18 at 13:22
add a comment |
Generic constraints will be combined by AND, so where T : IBaseModel, IList<IBaseModel>
means T
should implement both IBaseModel
and IList<IBaseModel>
.
You need to create two methods:
public async Task<T> Get<T>(string url) where T : IBaseModel
public async Task<IList<T>> GetList<T>(string url) where T : IBaseModel
Generic constraints will be combined by AND, so where T : IBaseModel, IList<IBaseModel>
means T
should implement both IBaseModel
and IList<IBaseModel>
.
You need to create two methods:
public async Task<T> Get<T>(string url) where T : IBaseModel
public async Task<IList<T>> GetList<T>(string url) where T : IBaseModel
edited Dec 30 '18 at 12:54
answered Dec 30 '18 at 12:42
Reza AghaeiReza Aghaei
65.8k854162
65.8k854162
If these two methods are member of the same class which can have<T>
as common generic constraint, moveT
to generic parameters of the class.
– Reza Aghaei
Dec 30 '18 at 13:22
add a comment |
If these two methods are member of the same class which can have<T>
as common generic constraint, moveT
to generic parameters of the class.
– Reza Aghaei
Dec 30 '18 at 13:22
If these two methods are member of the same class which can have
<T>
as common generic constraint, move T
to generic parameters of the class.– Reza Aghaei
Dec 30 '18 at 13:22
If these two methods are member of the same class which can have
<T>
as common generic constraint, move T
to generic parameters of the class.– Reza Aghaei
Dec 30 '18 at 13:22
add a comment |
You can use another class which implements both IBaseModel and IList, and then T is constrained to this class.
public class DerivedModel : IBaseModel, IList<IBaseModel>
{
private int _size;
private IBaseModel _items=new IBaseModel[1000];
private int _version;
public int Id { get; set; }
public IEnumerator<IBaseModel> GetEnumerator()
{
throw new NotImplementedException();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
...
}
And the generic method is:
public async Task<T> Get<T>(string url) where T : DerivedModel
{
return await Task<T>.Factory.StartNew(() =>
{
var derivedModel = new DerivedModel() {new BaseModel() {Id = 1}};
return (T) derivedModel;
});
}
In which the IBaseModel and BaseModel can be:
public interface IBaseModel
{
int Id { get; set; }
}
public class BaseModel : IBaseModel
{
public int Id { get; set; }
}
The usage:
var inheritance=new Inheritance();
var result = await inheritance.Get<DerivedModel>("aaa");
textBox1.Text = result[0].Id.ToString();
add a comment |
You can use another class which implements both IBaseModel and IList, and then T is constrained to this class.
public class DerivedModel : IBaseModel, IList<IBaseModel>
{
private int _size;
private IBaseModel _items=new IBaseModel[1000];
private int _version;
public int Id { get; set; }
public IEnumerator<IBaseModel> GetEnumerator()
{
throw new NotImplementedException();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
...
}
And the generic method is:
public async Task<T> Get<T>(string url) where T : DerivedModel
{
return await Task<T>.Factory.StartNew(() =>
{
var derivedModel = new DerivedModel() {new BaseModel() {Id = 1}};
return (T) derivedModel;
});
}
In which the IBaseModel and BaseModel can be:
public interface IBaseModel
{
int Id { get; set; }
}
public class BaseModel : IBaseModel
{
public int Id { get; set; }
}
The usage:
var inheritance=new Inheritance();
var result = await inheritance.Get<DerivedModel>("aaa");
textBox1.Text = result[0].Id.ToString();
add a comment |
You can use another class which implements both IBaseModel and IList, and then T is constrained to this class.
public class DerivedModel : IBaseModel, IList<IBaseModel>
{
private int _size;
private IBaseModel _items=new IBaseModel[1000];
private int _version;
public int Id { get; set; }
public IEnumerator<IBaseModel> GetEnumerator()
{
throw new NotImplementedException();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
...
}
And the generic method is:
public async Task<T> Get<T>(string url) where T : DerivedModel
{
return await Task<T>.Factory.StartNew(() =>
{
var derivedModel = new DerivedModel() {new BaseModel() {Id = 1}};
return (T) derivedModel;
});
}
In which the IBaseModel and BaseModel can be:
public interface IBaseModel
{
int Id { get; set; }
}
public class BaseModel : IBaseModel
{
public int Id { get; set; }
}
The usage:
var inheritance=new Inheritance();
var result = await inheritance.Get<DerivedModel>("aaa");
textBox1.Text = result[0].Id.ToString();
You can use another class which implements both IBaseModel and IList, and then T is constrained to this class.
public class DerivedModel : IBaseModel, IList<IBaseModel>
{
private int _size;
private IBaseModel _items=new IBaseModel[1000];
private int _version;
public int Id { get; set; }
public IEnumerator<IBaseModel> GetEnumerator()
{
throw new NotImplementedException();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
...
}
And the generic method is:
public async Task<T> Get<T>(string url) where T : DerivedModel
{
return await Task<T>.Factory.StartNew(() =>
{
var derivedModel = new DerivedModel() {new BaseModel() {Id = 1}};
return (T) derivedModel;
});
}
In which the IBaseModel and BaseModel can be:
public interface IBaseModel
{
int Id { get; set; }
}
public class BaseModel : IBaseModel
{
public int Id { get; set; }
}
The usage:
var inheritance=new Inheritance();
var result = await inheritance.Get<DerivedModel>("aaa");
textBox1.Text = result[0].Id.ToString();
answered Dec 31 '18 at 4:12


Vahid AsbaghiVahid Asbaghi
11
11
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53977528%2fcreating-a-generic-method-in-c-sharp-through-specific-where-clause%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
JdrvW 9l,I
2
You cannot cast a list of a derived type to a list with the base class. That would allow for other types with the same base class to be added to that list.
– Biesi Grr
Dec 30 '18 at 12:38
1
How
List<DrivedClassFromBaseModel>
could beIBaseModel
?– Reza Aghaei
Dec 30 '18 at 12:40
You should be able to do Task<List<T>> Get<T>(string url) where T : IBaseModel
– stannius
Dec 30 '18 at 12:58
@Reza Aghaei DrivedClassFromBaseModel:IBaseModel
– Saman Gholami
Dec 30 '18 at 14:42
1
I see, but
DrivedClassFromBaseModel:IBaseModel
doesn't meanList<DrivedClassFromBaseModel>
isIBaseModel
. As it's already mentioned in the answer,where T : IBaseModel, IList<IBaseModel>
meansT
should implement bothIBaseModel
andIList<IBaseModel>
.– Reza Aghaei
Dec 30 '18 at 18:57