I've been trying this, but I can't seem to figure this out. I want to do this...
public abstract class SingletonType<TSingleton, TBaseClass> : TBaseClass where TSingleton : TBaseClass, new() where TBaseClass : class { static TSingleton _singleton; public static TSingleton Singleton => _singleton ?? (_singleton = new TSingleton()); }
The plan was to use it like this which would sort of 'wrap' the singleton pattern around a base class...
public class SingletonFoo : SingletonType<SingletonFoo, Foo> { }
However, I keep getting this
Cannot derive from 'TBaseClass' because it is a type parameter
Um... I thought types were exactly what you do derive from!
So what am I missing?
Note: This is, of course, a trivial example as it doesn't add anything helpful, but assume SingletonType
has a lot of other logic which isn't relative to the question, hence it was omitted to focus on the question at hand.
The not-equal-to operator ( != ) returns true if the operands don't have the same value; otherwise, it returns false .
In mathematics, the tilde often represents approximation, especially when used in duplicate, and is sometimes called the "equivalency sign." In regular expressions, the tilde is used as an operator in pattern matching, and in C programming, it is used as a bitwise operator representing a unary negation (i.e., "bitwise ...
Summary. An operator is a symbol which operates on a variable or value. There are types of operators like arithmetic, logical, conditional, relational, bitwise, assignment operators etc. Some special types of operators are also present in C like sizeof(), Pointer operator, Reference operator etc.
Generic types in C# are not C++ templates; remember, a generic type must work for all possible type arguments. A template need only work for the constructions you actually make.
This question is a duplicate; see my answer to
Why cannot C# generics derive from one of the generic type parameters like they can in C++ templates?
for more thoughts on this. Basically, the short answer is that the considerable costs do not outweigh the small benefits of the feature. If you don't like that answer, see my second answer:
Why cannot C# generics derive from one of the generic type parameters like they can in C++ templates?
And if you don't like that answer either, see the follow-up question:
What are the good reasons to wish that .NET generics could inherit one of the generic parameter types?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With