What is the java equivalent bounded wildcard in C# properties? [duplicate] - c#

This question already has answers here:
C#'s equivalent of Java's <? extends Base> in generics
(4 answers)
Closed 9 years ago.
I’m looking for equivalent C# code of following line
private List<? extends HotSpot> hotSpots;
Any help is much appreciated.

Depending on exactly what you need, you're probably either looking for:
public class MyClass
{
private IList<HotSpot> hotSpots;
}
or using where
public class MyClass<T> where T : HotSpot
{
private IList<T> hotSpots;
}

Functionally, I'd say the closest is:
IEnumerable<HotSpot> hotSpots;
If the real type of the the enumerable happens to be an IList, then ElementAt() and such will be O(1).
As of .NET 4.5, you could also use:
IReadOnlyList<HotSpot> hotSpots;
and use List.AsReadOnly() to wrap regular lists.
The .NET approach to variance in generics is letting specific interfaces be either covariant or contravariant, and consequently only allow them to define methods with the generic type parameter as the return value only, or only in the argument list. (As opposed to Java where the compiler does these checks in each expression.) My guess is the rationale is that C# implements generics using reification, and a concrete type like List<out T> can't exist in the type system.

Related

Getting a type representation of a partially open generic type [duplicate]

This question already has answers here:
C# Language: How to get type of bound but open Generic class?
(4 answers)
Closed 6 years ago.
I am wondering if anyone knows a way to get a representation of a partially open generic type in C#, for example IDictionary<string,>.
What I have tried:
typeof(IDictionary<string,>)
I get: Partially opened type is not permitted in 'typeof' expression compile error.
typeof(IDictionary<,>).MakeGenericType(typeof(string))
I get: ArgumentException (The number of generic arguments provided doesn't equal the arity of the generic type definition. Parameter name: instantiation)
Why I want to do this:
I have a number of scenarios where I need to check if a class I have implements an interface, but in several cases I know that some of the generic type parameters have to be specific (i.e. I want something that implements a dictionary with string keys but I don't care about the value type). I realize there are a number of other ways I could do this (for example, by providing an array of necessary generic parameter types to my method). But in looking at the problem I got curious if there is a way to specify partially open / partially closed generic types, hence the question.
Maybe something like that could answer to your problem:
class CustomDictionary<TValue> : Dictionary<string, TValue>
{
}
And this should work:
typeof(CustomDictionary<>).MakeGenericType(typeof(string))

Why generic classes in .Net are invariant towards theirs generic args? [duplicate]

This question already has an answer here:
Why do I need an Interface for Covariance (out Type)?
(1 answer)
Closed 8 years ago.
Why in .Net templating a generic class is an invariant operation towards generic arguments?
Interfaces and delegates are not, but classes are.
For instance, I would like to be able to assign object of type Expression<Func<string>> to Expression<Func<object>>. As T in Func<T> is "out" and Expression is immutable, it would be reasonable to assign it as I have showed, right?
Had classes allowed variant type parameters, you wouldn't be able to use them in any field, since fields are always (at least sometimes) writable and readable.
That would limit the utility enough to make it not worth it.

When to use IList or List [duplicate]

This question already has answers here:
When to use IList and when to use List
(12 answers)
Closed 9 years ago.
I saw a function like
public FuncA(string param1, IList<SqlParameter> sqlParamsList)
I wonder why the author was using IList instead of List? Which one is better? I know the difference between them is one is interface, the other one is class. So my final question is when to use which?
More than one class can implement the IList interface. If you use IList you accept any class that implements IList.
If you use List, you can only pass List and derived classes.
Using an interface is generally preferable as it makes the API more flexible for the caller. If your method accepts the interface rather than the concrete implementation, the caller can use whatever type they want (List, Array, ImmutableList...), as long as it implements IList.
Using an interface is preferred over a concrete type in order to allow a caller to pass in any object that implements the interface.
Especially in public methods this is good practice.
I would tend towards using the IList interface parameter over the concrete implementation, unless there was some reason you absolutely HAD to have the concrete List parameter.
By using IList instead of List, your method can now accept all collection types that implement IList, which may or may not be a collection that directly inherits from List. List and any of its subclasses implement IList as well, so they would also be included in the set of available types your method could use. Using IList in this case allows you to be more flexible.
Also, in unit testing scenarios, IList may be easier to mock out, depending on what exactly you're trying to test and what your features your mocking framework has.

System.Enum as a generic type parameter with constraints [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Create Generic method constraining T to an Enum
Enum type constraints in C#
Consider the following class:
public class Transition<TState>
{
public Transition ()
{
if (!typeof(TState).IsEnum)
throw (new ArgumentException("[TState] has to be of type [System.Enum]."));
}
}
Ideally, this should be declared as:
public class Transition<TState> where TState: System.Enum
{
}
The above, of course, generates a compile-time error. My question is why has that been made illegal. Most sources explain say that it is illegal but do not explain why. Any thoughts?
As Eric Lippert says that and I quote
ALL features are unimplemented until someone designs, specs, implements, tests, documents and ships the feature. So far, no one has done that for this one. There's no particularly unusual reason why not; we have lots of other things to do, limited budgets, and this one has never made it past the "wouldn't this be nice?" discussion in the language design team."

Type Name aliasing in C# [duplicate]

This question already has answers here:
Closed 13 years ago.
Possible Duplicates:
typedef in C#?
STL like containter typedef shortcut?
I was wondering if there was an equivalent to Type aliasing from Functional Languages that I can use in C#
For example in a nice functional language like Haskell I can say something like the following to alias an existing type to a custom Type Name
type MyCustomTypeName = String
I'd like to do this as I have an API that I'm building where some of the Objects I'm using have multiple possible names in the sense they could be referred to by several terms which are interchangeable and equivalent. Presumably I could do this with inheritance but that seems somewhat clunky and then potentially breaks if people start extending the non-canonical class ie.
public class CanonicalClass {
//Full Implementation
}
public class AlternateName : CanonicalClass {
//Empty except I'll need to redefine all the constructors
//Could declare it sealed but doesn't get rid of the need to redefine constructors
}
And before anyone mentions interfaces all the Classes in question are all implementing interfaces already and there are multiple differing implementations of these interfaces.
Depending on what you're actually trying to do (give a somewhat more complete example), you may indeed need interfaces (used properly) and/or generics.

Categories