Is it possible to create generic restriction in C# using where to select only classes, who have Field with some name.
for example, I have AbstractService<T>
and I have a method IEnumerable<T> ProvideData(userId);
inside provide data I should select only instances with the same user bla-bla-bla.Where(d => d.UserId == userId). But d.UserId could not be resolved. How it possible to resolve this?
IMPORTANT: I can’t inherit T from class or interface, which have UserID field.
An interface is what your are looking for:
[Edit] As you edited your question to state you cannot change class to implement an interface, here is some alternatives, but none relies on generic constraint :
code :
code :
If your source classes are generated, you can cheat. I used this technique with lots of Web References having the same kind of parameter objects
Imagine the Web references produced this proxy code :
You can wrap them using in your own code:
then, for your service, you can instantiate AbstractService for any of the Class of the several web services :
This technique works great but only applies when you can extend class in the same project because of the partial keyword trick.