Can anyone help me in using Where for generic types?
I was trying to create a function which does ST with a number of type double or int, so I said it should be generic function. But when I try to assign a value to variables of that generic type, I can't because it's not a numerical type. Also, I can't use Where to inherit generic type from int or double data types.
Here is the code:
public static T[,] Unit(int n) where T : PROBLEM
{
T[,] mat = new T[n, n];
for (int i = 0; i < n; i++)
mat[i, i] = (T)1;
return mat;
}
Can anyone help?
Unfortunately one of the shortcomings of C# is that you cannot easily make generic numerical algorithms. You can kind of hack around it, like using this example from MSDN:
public abstract class BaseCalculator<T>
{
public abstract T Add(T arg1,T arg2);
public abstract T Subtract(T arg1,T arg2);
public abstract T Divide(T arg1,T arg2);
public abstract T Multiply(T arg1,T arg2);
}
public class IntCalculator : BaseCalculator<int>
{
public override int Add(int arg1, int arg2)
{
return arg1 + arg2;
}
//Rest of the methods
}
But generally speaking the .Net libraries just have a separate implementation for this sort of thing rather than attempting to use generics.
Not sure what this "Where" is to which you are referring, but you can declare your generic function as
public T Calculate<T>(T x, T y) where T : IComparable<T>
{
// do calculations
}
I believe int and double both implement IComparable<T>.
The constraints system in Generics is still pretty coarse grained. Its still a blunt tool with relatively few options to choose from. A much richer feature set for expressing constraints on type parameters will allow all sorts of sophisticated algos to be designed like pattern based programming etc.
If you only tell me that T is a shirt type that I am looking at ... there aint much I can do with it. But if T is not only a shirt but is actually worn by a hooter with some int[] properties with counts in upper 30's and certain events that I can subscribe to and handle with custom codes then I think it will make programming a little more fun and lively.
You can constrain your generic type parameter to be a struct. Struct represents a value type like int or double. Here's an example from the MSDN article:
public class MyClass<T> where T : struct
{...}
Related
static void Main(string[] args)
{
AbsValue<int> ABS = new AbsValue<int>();
AbsValue<double> ABSdouble = new AbsValue<double>();
ABS.X = -5;
ABSdouble.X = 65.3;
Console.WriteLine("Integer absolute value: {0}", Math.Abs(ABS.X));
Console.WriteLine("Double absolute value: {0}", Math.Abs(ABSdouble.X));
Console.ReadLine();
}
}
I don't think that it is correctly, but it seems to work. Can you please give me some advise, how i can make it better?
class AbsValue<T>
{
public T X;
}
There's not a clean way to wrap Math.Abs into a generic function, because 1) the function is not generic but instead designed with overloads for each numeric type, and 2) creating a generic restraint for numeric types is not possible in .NET1.
Even if you did that you'd still have to have a giant switch statement to call the proper Math.Abs overload.
I think I'd find a different problem to solve as a beginner - this one is not an easy learning exercise.
1 You can get close by constraining the parameter to struct, IComparable, IFormattable, but it doesn't really buy you much as you'd have to cast to use any operators or framework math functions.
If you want to do Abs generically you can create an interface and implement it for double and int e.g.:
public interface IAbsNum<T>
{
T Abs(T num);
}
public class IntAbsNum : IAbsNum<int>
{
public int Abs(int num) { return Math.Abs(num); }
}
I'm writing, in C#, an interpreter for a dynamic language, and implementing primitive functions as an abstract class Primitive with a virtual Apply method, where each actual primitive function will be a subclass that overrides Apply.
(An alternative would be to only have the class Primitive and store a function pointer for Apply. However, making it a virtual method seems likely to be slightly faster, and this code will be run very frequently, so a small speedup is worth having.)
Obviously I could go ahead and create a full-blown class file for each primitive function, but I can't help feeling there ought to be a slightly more concise way of doing things than creating dozens of tiny class files.
In Java I'd use the anonymous subclass syntax to create and instantiate a subclass all in one expression, but I don't think C# has an exact counterpart.
What is the best way of doing this in C#?
Firstly, I wouldn't assume that a virtual method call will be faster than a delegate. Maybe it will, maybe it won't - but if performance is really that important to you, you should measure that. It would be really simple to code this using lambda expressions, particularly if all you're trying to represent is a function:
public static readonly Func<int, int> Addition = (x, y) => x + y;
public static readonly Func<int, int> Subtraction = (x, y) => x - y;
// etc
(I'm just guessing at the sorts of operation here, as we don't know the details.)
There's no particularly tiny syntax for subclasses in C#, but for semi-singletons like this
I find nested classes work well... similar to Java enums:
public abstract class Primitive
{
public static readonly Primitive Addition = new AdditionPrimitive();
public static readonly Primitive Subtraction = new SubtractionPrimitive();
// Prevent outside instantiation
private Primitive()
{
}
public abstract int Apply(int x, int y);
// Anything else you want
private class AdditionPrimitive : Primitive
{
public override int Apply(int x, int y)
{
return x + y;
}
}
private class SubtractionPrimitive : Primitive
{
public override int Apply(int x, int y)
{
return x - y;
}
}
}
This is an attempt to learn Generics (with .Net 4.0). I have been programming for about 4.5 years. Till now I have not used Generics in real time projects. All the time what I have been doing is reading some article about generics and try to understand it. The problem is – most of them try to explains various syntax available with Generics. They explain with examples such as Square, Circle and shapes.
Now I have got a chance to design a small application. I would like to use Generics there. [I do see good chances of Generics being a good candidate in my new project]
What I have come up with now is an example from Bank domain with the intention of understanding Generics. I am trying to understand the following 4.
1) Generic classes
2) Generic Methods
3) Generic Interfaces
4) Generic Delegates
EDIT: Operations that are type-independant are good candidates for generics. This is the one of the biggest points I missed in my following example.
I have created an example for “Generic classes”. Could you please help with simple examples for other three items with the Bank domain?
Note: While using Generic class, I came to know that it helped in Open-Closed Principle. Even if I add new account type, the generic class need to change. The changing logic (interest calculation) goes inside the specific class.
Note: In the following, the syntax may not be correct as it typed it without a Visual Studio. But the concept holds good.
EDIT: Will "AccountManager" be a more better name for "BankAccount" class based on its role? Is it any kind of anti-pattern?
Generic Class - Example with Bank Domain
Public Interface IBankAccount
{
Public int Interest;
Public Int DepositedAmount;
Public int DurationInMonth;
}
Public class FixedAccount: IbankAccount
{
Public int Interest
{
Get
{
Return (DurationInMonth*0.5)
}
}
Public Int DepositedAmount {get;set};
Public int DurationInMonth {get;set};
}
Public class SavingsAccount: IbankAccount
{
Public int Interest
{
Get
{
Return ((DurationInMonth/2)*0.1)
}
}
Public Int DepositedAmount {get;set};
Public int DurationInMonth {get;set};
}
Public Class BankAccount<T> Where T: IbankAccount
{
T account = new T();
Public void CreateAccount(int duration, int amount)
{
account. DurationInMonth = duration;
account. DepositedAmount = amont;
int interestVal = account. Interest;
SaveToDatabase (T);
}
}
READING:
When is it Appropriate to use Generics Versus Inheritance?
Generics vs inheritance (when no collection classes are involved)
https://codereview.stackexchange.com/questions/8797/how-to-make-sure-that-this-code-conforms-to-open-close-principle
A Factory Pattern that will satisfy the Open/Closed Principle?
I'm having some trouble with generics and casting in C#
Deciding When and Where to Use Generics
http://en.csharp-online.net/CSharp_Generics_Recipes—Deciding_When_and_Where_to_Use_Generics_Problem
Code reuse through generics vs polymorphism
Polymorphism AND type safety in parallel inheritance chains
Extending using C# generics?
C# Generics and polymorphism: an oxymoron?
Shoe-horning generics into a project just because "I want to use generics" is usually a bad idea. use the right tool for the right job. now, props for trying to learn something new.
that said...
Basically, a "generic" is a way of specifying a method, class (etc) without specifying an underlying type when you write it. It is a good way to separate your algorithm from you data type.
take, for example, a Swap method. Basically, the swap algorithm is the same no matter what the type it is operating on. So, this would be a good candidate for a generic (as would a List, a Dictionary, etc)
so, a swap for an int would like like this:
void Swap(ref int left, ref int right)
{
int temp = left;
left = right;
right = temp;
}
now, you COULD write overloads for your other datatypes (float, double, etc)
or you COULD make it a generic and write it once so it will work on pretty much all datatypes:
void Swap<_type>(ref _type left, ref _type right)
{
_type temp = left;
left = right;
right = temp;
}
now, your sample code wont work:
Public void CreateAccount(int duration, int amount)
{
T.DurationInMonth = duration;
T.DepositedAmount = amont;
int interestVal = T.Interest;
SaveToDatabase (T);
}
here, T is the type, not an instance of an object. if you substitute for T, it becomes clearer what is going on:
Public void CreateAccount(int duration, int amount)
{
IbankAccount.DurationInMonth = duration;
IbankAccount.DepositedAmount = amont;
int interestVal = IbankAccount.Interest;
SaveToDatabase (IbankAccount);
}
when what you REALLY want is this:
Public void CreateAccount(int duration, int amount)
{
account.DurationInMonth = duration;
account.DepositedAmount = amont;
int interestVal = account.Interest;
SaveToDatabase (account);
}
you see, here we are calling the methods of the INSTANCE of the class account, not of the generic IbankAccount TYPE
Just my two cents, since #Lijo asked me to comment here.
I would go with most of the above answers.
But to summarise, Generics is typeless reuse of behaviour. The fact that your generic type has to be an IBankAccount -which is a very specific interface - is saying this probably is not right. I am not saying that you cannot use restrictions for an interface but that interface would be a very generic interface itself such as IDisposable or IConvertible.
Generics are about generic type parameters. If you want to program something and you do not know for which type it will be applied in advance, you would declare a generic type parameter.
class MyStore<T>
{
}
Here T is a generic type parameter. You do not know for which type it stands for.
You could write something like this
class MyStore<T>
{
public void Store(T item)
{
...
}
public T Retrieve()
{
...
}
}
Now you can use MyStore like this:
var stringStore = new MyStore<string>();
stringStore.Store("Hello");
string s = stringStore.Retrieve();
var intStore = new MyStore<int>();
intStore.Store(77);
int i = intStore.Retrieve();
You could also declare the store like this; however, it would not be type safe
class MyStore
{
public void Store(object item)
{
...
}
public object Retrieve()
{
...
}
}
You would have to cast the results
var stringStore = new MyStore();
stringStore.Store("Hello");
string s = (string)stringStore.Retrieve();
var intStore = new MyStore();
intStore.Store(77);
int i = (int)intStore.Retrieve();
var doubleStore = new MyStore();
doubleStore.Store("double");
double d = (double)doubleStore.Retrieve(); // OOPS! A runtime error is generated here!
0) Using .NET's generic collections with your types as container types: Suppose you want to list all the accounts associated with a specific customer, and display them in a data grid. A List<IBankAccount> would be helpful, or a Dictionary<ICustomerID,IBankAccount> if you wanted to look at more than one customer's account.
1,2) Creating your own generic class and generic methods: Say you want to perform a calculation which involves all accounts in order to generate a report. In this particular report, numerical precision is not important, and speed is. So you could use Single insted of Decimal. In this particular case, to make the classes involved in the calculation independent of the numeric type used, using a generic argument is more natural than inheritance. Pseudo code:
public class MetricCalculator<T>{
private bool _dirty;
private T _cachedValue;
T PerformCalculation(){
if( !_dirty )
return cachedValue;
T metric = 0;
foreach( IBankAccount account in AccountMapper.GetAll() ){
T += account.Foo * accound.Bar;
}
_cachedValue = metric;
return metric;
}
}
In this example, MetricCalculator is a generic class because one of its data members is of the parameterized type. That member is used to avoid repeating the calculation if the values used haven't changed. There is also a generic method, which performs calculations without caring about the numeric type used. If there were no need to cache the value, you could have just a common class with a generic method. I combined both just to save space.
3) Generic interface: Suppose you want to completely decouple all your components (to implement Inversion of Control, for example) ; in that case, if you had generic classes like MetricCalculator that were used across assemblies, you'd need to use them via a generic interface. Another example would be if you needed to write a custom data structure or iterator, but I doubt you'd have to come to that.
4) Generic events: Back to the MetricCalculator example, suppose that you want to notify some observer object with an event that notifies that the calculation is done, and pass the result. It would be like an usual event, but you'd pass an argument of type T when raising the event. Note: it might be better to use C#5's async-await feature if available.
I want to restrict the possible types N can take-on using a constraint. I wish to restrict N to be either a int or a decimal.
public static Chart PopulateInto<T, N>(List<T> yAxis, List<N> xAxis) where N : int, decimal
{
// Do stuff here
}
Any help appreciated...
It's not possible to constrain a generic parameter to a specific value type.
You can however force it to be a value type or struct by adding where N : struct, but that's all.
Unfortunately, it is not possible to specify generic type constraints that only allow specific value types. More to the point, it wouldn't make much sense even if it was allowed.
You're allowed to specify a class as a generic constraint but this is because you can inherit from classes, the constraint thus sets the minimum threshold of what types you're allowed to use.
If this was allowed for value types, where you cannot inherit from those types, you would effectively limit yourself to only that type.
Thus you cannot do this, but you have a few alternatives:
You can declare it without the constraint, and handle the problem at runtime. I would not recommend this way
You can declare overloads that take the specific types you're interested in.
Since you only have two such types this is what I would recommend doing.
Here are the overloads you would declare:
public static Chart PopulateInto<T>(List<T> yAxis, List<int> xAxis)
{
// Do stuff here
}
public static Chart PopulateInto<T>(List<T> yAxis, List<decimal> xAxis)
{
// Do stuff here
}
Now, additionally, if your handling of those values doesn't really rely on the numeric quality of those types, you just want to limit which types you can handle, then you can always declare your original method as well, privately, and call this method from your overloads. This would still limit your code to only allowing int or decimal, publicly, but your implementation would still be generic. Without knowing exactly what "Do stuff here" entails it is impossible to tell if this is a viable option or not but here is the code anyway:
public static Chart PopulateInto<T>(List<T> yAxis, List<int> xAxis)
{
return PopulateInto<T, int>(yAxis, xAxis);
}
public static Chart PopulateInto<T>(List<T> yAxis, List<decimal> xAxis)
{
return PopulateInto<T, decimal>(yAxis, xAxis);
}
private static Chart PopulateInto<T, N>(List<T> yAxis, List<N> xAxis) where N : struct
{
// Do stuff here
}
There is no way to do this with a constraint. Another approach though, assuming that PopulateInto can work with a generic N, is to make the core algorihtm generic and private and offer 2 public overloads which take an int and decimal respectively. This will create a similar effect
public static Chart PopulateInto<T>(
List<T> yAxis,
List<decimal> xAxis) {
return PopulateIntoCore(yAxis, xAxis);
}
public static Chart PopulateInto<T>(
List<T> yAxis,
List<int> xAxis) {
return PopulateIntoCore(yAxis, xAxis);
}
private static Chart PopulateIntoCore<T, N>(
List<T> yAxis,
List<N> xAxis) where N : struct {
...
}
To answer the question in the Title but not the body of the question.
To cover all types commonly meant by Value Types (which includes Nullable Value Types, and also string even though it's technically a Reference type), you need 3 overloads:
public void Foo<T>(T arg) where T : struct
public void Foo<T?>(T? arg) where T : struct
public void Foo<string>(string arg)
From the MSDN Docs on generic constraints:
where T : struct The type argument must be a non-nullable value type.
As Pieter said, you cannot use a compile-time check to to this. However, you can do the following at runtime:
if(!(typeof(N).equals(typeof(int32))) && !(typeof(N).equals(typeof(decimal))))
// do something
The closet you can get is Where T: struct, IComparable, IFormattable, IConvertible.
All value types implements these interfaces.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
C# generic constraint for only integers
Greets!
I'm attempting to set up a Cartesian coordinate system in C#, but I don't want to restrict myself to any one numerical type for my coordinate values. Sometimes they could be integers, and other times they could be rational numbers, depending on context.
This screams "generic class" to me, but I'm stumped as to how to constrict the type to both integrals and floating points. I can't seem to find a class that covers any concept of real numbers...
public class Point<T> where T : [SomeClassThatIncludesBothIntsandFloats?] {
T myX, myY;
public Point(T x, T y) {
myX = x;
myY = y;
}
}
Point<int> pInt = new Point<int>(5, -10);
Point<float> pFloat = new Point<float>(3.14159, -0.2357);
If I want this level of freedom, am I electing for a "typeof(T)" nightmare when it comes to calculations inside my classes, weeding out bools, strings, objects, etc? Or worse, am I electing to make a class for each type of number I want to work with, each with the same internal math formulae?
Any help would be appreciated. Thanks!
You can't define such a constraint, but you could check the type at runtime. That won't help you for doing calculations though.
If you want to do calculations, something like this would be an option:
class Calculations<T, S> where S: Calculator<T>, new()
{
Calculator<T> _calculator = new S();
public T Square(T a)
{
return _calculator.Multiply(a, a);
}
}
abstract class Calculator<T>
{
public abstract T Multiply(T a, T b);
}
class IntCalculator : Calculator<int>
{
public override int Multiply(int a, int b)
{
return a * b;
}
}
Likewise, define a FloatCalculator and any operations you need. It's not particularly fast, though faster than the C# 4.0 dynamic construct.
var calc = new Calculations<int, IntCalculator>();
var result = calc.Square(10);
A side-effect is that you will only be able to instantiate Calculator if the type you pass to it has a matching Calculator<T> implementation, so you don't have to do runtime type checking.
This is basically what Hejlsberg was referring to in this interview where the issue is discussed. Personally I would still like to see some kind of base type :)
This is a very common question; if you are using .NET 3.5, there is a lot of support for this in MiscUtil, via the Operator class, which supports inbuilt types and any custom types with operators (including "lifted" operators); in particular, this allows use with generics, for example:
public static T Sum<T>(this IEnumerable<T> source) {
T sum = Operator<T>.Zero;
foreach (T value in source) {
if (value != null) {
sum = Operator.Add(sum, value);
}
}
return sum;
}
Or for another example; Complex<T>
This is a known problem, since none of the arithmetic classes arrive from the same class. So you cannot restrict it.
The only thing you could do is
where T : struct
but thats not exactly what you want.
Here is a link to the specific issue.
Arithmetic types like int,double,decimal should implement IArithmetic<T>
You actually can do this, although the solution is tedious to set up, and can be confusing to devs who are not aware of why it was done. (so if you elect to do it document it thououghly!)...
Create two structs, called say, MyInt, and MyDecimal which act as facades to the CTS Int32, and Decimal core types (They contain an internal field of that respective type.) Each should have a ctor that takes an instance of the Core CTS type as input parameter..
Make each one implement an empty interface called INumeric
Then, in your generic methods, make the constraint based upon this interface.
Downside, everywhere you want to use these methods you have to construct an instance of the appropriate custom type instead of the Core CTS type, and pass the custom type to the method.
NOTE: coding the custom structs to properly emulate all the behavior of the core CTS types is the tedious part... You have to implement several built-in CLR interfaces (IComparable, etc.) and overload all the arithmetic, and boolean operators...
You can get closer with implementing few more
public class Point<T> where T : struct, IComparable, IFormattable, IConvertible,
IComparable<T>, IEquatable<T> {
}
The signature conforms to DateTime too. I'm not sure if you will be able to specify more types from the framework. Anyway this only solves part of the problem. To do basic numeric operations you will have to wrap your numeric types and use generic methods instead of standard operators. See this SO question for a few options.
This might be helpful. You have to use a generic class to achieve what you want.
C# doesn't currently allow type constraints on value types. i asked a related question not too long ago.
Enum type constraints in C#
Would this not lend itself to having seperate classes implementing IPoint?
Something like:
public interface IPoint<T>
{
T X { get; set; }
T Y { get; set; }
}
public class IntegerPoint : IPoint<int>
{
public int X { get; set; }
public int Y { get; set; }
}
As the calculations will have to differ in each implementation anyway right?
Dan#