C# Inheritance after double - c#

I would like to add some functions to double type. I created new class "ExtraDouble" and I I want to class behave as double.
For example: I have:
class ExtraDouble{
double myVar = 0.59;
}
And, wherever:
Extradouble e = new Extradouble();
String.Format("Value of e is: {0}", e) // return: Value of e is: 0.59
Is it possible?
Default using "e" must return value of variable "myVar" (without any accessors)

Yes. All objects have a virtual ToString method. For your case, just override that:
class ExtraDouble
{
double myVar = 0.59;
public override string ToString()
{
return myVar.ToString();
}
}
For more completeness. If you want your ExtraDouble to behave as a double in common scenarios (like performing arithmetic operations), you can use the implicit keyword:
class ExtraDouble : Object
{
double myVar = 0.59;
public override string ToString()
{
return myVar.ToString();
}
public static implicit operator double(ExtraDouble d)
{
return d.myVar;
}
}
Then you can do things like:
Console.WriteLine(5 * new ExtraDouble());

If I understand you question correctly, you want to class that behaves like a double but with extended functionality. You could take a look at object extensions. They are designed to extend classes that you do not normally have access to inherit.
public static class DoubleExtension
{
public static double Sqr(this double d)
{
return d * d;
}
}
This will make it look like the Sqr() is a method of the type double.
E.g.
double d = 2.0f;
double sqrD = d.Sqr();
// This value will now be 4. This call looks like a class method but its not, it's an extension

Related

Is it possible to change the parameters that a predefined method can take in C#?

Im not sure if this is possible. Im using a method that takes the parameter int but i found myself in a situation where i need to be able to use a float value. Does anyone know if there is anyway to change the parameters that a predefined method can take?
Thanks All
Best
Alex
You can overload a method as follows:
public static float myMethod(float sumNumber)
{
// whatever you need for code here
return sumNumber;
}
public static int myMethod(int sumNumber)
{
// whatever you need for code here
return sumNumber;
}
C# has generics for his type of requirement, where you want to apply a logic indifferent of the type of parameter input
for example :
T foo<T>(T param)
{
return param + 1;
}
//and it can be used like this
int i;
foo<int>(i); // return type is int
float f;
foo<float>(f); // return type is float
Member overloading means creating two or more members on the same type that differ only in the number or type of parameters but have the same name. - Microsoft MSDN
// your method
public static double Inc(int i)
{
return i + 1;
}
// your method (overloaded)
public static double Inc(double d)
{
return d + 1;
}
int i = Inc(3);
double d = Inc(2.0); // You can use the same method with different parameter types
The website www.dotnetperls.com has a lot of nice examples. If you want to see another explanation besides MSDN, you may read this.
You can define a generic class for such methods.
public class GenericMethodsClass<T>
{
public static T myMethod(T sumNumber)
{
// whatever you need for code here
return sumNumber;
}
}
Calling:
GenericMethodsClass<int>.myMethod(1);
GenericMethodsClass<double>.myMethod(1.2);

C# generic constraints : Interface

I got a question for some code:
interface IDistance<T>
{
double distance();
double distance(T obj);
}
class Point<T> where T : IDistance<T> //why do i need this?
{
T obj;
public double dist(T val) { return obj.distance(val);
public Point(T obj) { this.obj = obj; }
}
class P2D : IDistance<P2D>
{
public double[] x = new double[2];
public P2D(double x, double y)
{
this.x[0] = x; this.x[1] = y;
}
public double distance()
{
double d = 0.0;
for (int i = 0; i < 2; i++) d = d + x[i] * x[i];
return Math.Sqrt(d);
}
public double distance(P2D val)
{
double d = 0.0;
for (int i = 0; i < 2; i++) d = d + Math.Pow(x[i]-val.x[i],2);
return Math.Sqrt(d);
}
}
class Tester
{
static void Main(string[] args)
{
P2D P1 = new P2D(3.0, 4.0);
Point<P2D> C1 = new Point<P2D>(P1);
Console.WriteLine(C1.dist());
}
}
The code in detail is rather unimportant.
Why do I need the constrain where T : IDistance<T> in the generic class Point<T>?
When I only specify classes that already implemented the interface IDistance<T> like
Class P2D, shouldn't be the interface already implemented implicit in the class Point?
I get the fact that it can cause problems, when a class as type <T> in class Point is defined that has not implemented the interface. But in this case, why is it not possible?
Look at this code within Point<T>:
T obj;
public double dist(T val) { return obj.distance(val);
When the compiler tries to understand what this expression means:
obj.distance(val)
it has to resolve the distance member. If T is unconstrained, it can't do that. When T is constrained to implement IDistance<T>, it can - it resolves it to the member of the interface.
In particular, without the constraint, I could use the type in very odd ways:
Point<string> weird = new Point<string>("foo");
double result = weird.dist("bar");
What would you expect that to do?
(As a side note, it would be worth following normal .NET naming conventions, even for examples. Methods should be PascalCased, and I'd never call a class P2D...)
When I only specify classes that already implemented the interface IDistance like Class P2D, shouldnt be the interface already implemented implicit in the Class Point? I get the fact that it can cause problems, when a class as type in Class Point is defined that has not implemented the interface. But in this case, why is it not possible?
Because C# is a language that has compile-time type safety. Without that constraint, you may only ever instantiate Point<T> with values of T at run-time which implement IDistance<T>, but there's no way for the compiler to know at compile-time that you will be so well-behaved.
why do i need this?
You need the constraint because you are restricting the generic type to be an implementation of the interface, IDistance<T>. If Point class you use some methods from this type like obj.distance(val);.
You also could use a abstract class to restrict derivations. Take a look at documentation in MSDN.
http://msdn.microsoft.com/en-us/library/bb384067.aspx
class Point<T> where T : IDistance<T> //why do i need this?
You need this becuase the class you declare, should take as type a type that implements the interface called IDistance<T>

Define default return value/function of a class?

Can I create a class with a default return value? Lets say if I create an object of this class I get always a specific value, without calling the properties or something else. Example:
int i = new MyIntClass(/*something*/); //will return an int
Actually I would like to use a default function for returning something. Maybe like this:
class MyCalculator()
{
public double a { get; set; }
public double b { get; set; }
MyCalculator(double a, double b)
{
this.a = a;
this.b = b;
}
public double DoMath()
{
return a*b;
}
}
/* somewhere else */
double result = new MyCalculator(5.5, 8.7);
result should be the result of DoMath(). Is that possible? I know its maybe not the best example, but something like this would be nice. Any ideas?
You can do an implicit cast.
Example (add to class):
public static implicit operator double(MyCalculator c)
{
return c.DoMath();
}
If I follow you, you want a MyCalculator to have a double it can be treated as. You can do this with an implicit cast operator overload. Put this in the definition of MyCalculator:
public static implicit operator double(MyCalculator m)
{
return m.DoMath();
}
However, it somewhat hides what's going on (you called new and got a double) and if you're a heavy user of var you'll find it annoying because you have to then be explicit.
In all, only use implicit if you have a very strong justification for it. Indeed, only use explicit if you have a very strong justification for it, and only use implicit if you've an extremely strong justification.
A good guideline for anything to do with a class' interface is "how sensible or weird will this look to someone who never sees the source code?"

where exactly implicit conversion method be put

public class Faranheit
{
public float Digree { get; set; }
public Faranheit(float f)
{
Digree = f;
}
public static implicit operator Celcius(Faranheit f)
{
return new Celcius((5.0f / 9.0f) * (f.Digree - 32));
}
public static implicit operator Faranheit(Celcius c)
{
return new Faranheit((9.0f / 5.0f) * c.Digree + 32);
}
}
public class Celcius
{
public float Digree{get;set;}
public Celcius(float c)
{
Digree = c;
}
}
I am just confused, where to put the conversion methods exactly..
It works fine even if I put one method in one class and other in the other, or I interchange them or even if I put both of them in any of the two classes..
But if I put it outside these two classes it doesn't work (compile error)..
Could please someone put some light on this..
EDIT:
if it allows the conversion methods to be in either of the class, why doesn't it allow the conversion method to be in a separate class??
All that matters is that the implicit conversion exists in one of the two classes. I would tend to put both conversions in the less-commonly used class.
In this case, the classes look equal, so I would put the conversion to the class in each class i.e. the conversion from F to C would go in the Celsius class, and vice versa.
Really, it's mostly about personal preference.
In this specific case, I would write a Temperature class that lets you get the temperature in C, F, K, R, etc. But that isn't exactly relevant to the actual question.
I would put them in each of the classes. So you can do stuff like:
Celsius c = new Celsius(Value);
Fahrenheit f = c.toFahrenheit();
Celsius newC = f.toCelsius();
edit: or if you wanted to go the Helper class route, you could do:
public static class ConvertTemps
{
public static Celsius toCelsius(Fahrenheit F)
{
return new Celsius(5/8* F - 32);
}
public static Fahrenheit toFahrenheit(Celsius C)
{
return new Fahrenheit(8/5*C + 32);
}
}
and then you could do things like:
Celsius c = new Celsius(value);
Fahrenheit f = ConvertTemps.toFahrenheit(c);
But I'd go the first route.

Implement math functions in custom C# type?

Could someone point me to the interface that I need to implement in order to get basic math operators (i.e. +, -, *, /) to function on a custom type?
You have to use operator overloading.
public struct YourClass
{
public int Value;
public static YourClass operator +(YourClass yc1, YourClass yc2)
{
return new YourClass() { Value = yc1.Value + yc2.Value };
}
}
public static T operator *(T a, T b)
{
// TODO
}
And so on for the other operators.
You can find a good example of operator overloading for custom types here.
public struct Complex
{
public int real;
public int imaginary;
public Complex(int real, int imaginary)
{
this.real = real;
this.imaginary = imaginary;
}
// Declare which operator to overload (+), the types
// that can be added (two Complex objects), and the
// return type (Complex):
public static Complex operator +(Complex c1, Complex c2)
{
return new Complex(c1.real + c2.real, c1.imaginary + c2.imaginary);
}
}
You need to overload the operators on the type.
// let user add matrices
public static CustomType operator +(CustomType mat1, CustomType mat2)
{
}
What you're looking for is not an interface, but Operator Overloading. Basically, you define a static method like so:
public static MyClass operator+(MyClass first, MyClass second)
{
// This is where you combine first and second into a meaningful value.
}
after which you can add MyClasses together:
MyClass first = new MyClass();
MyClass second = new MyClass();
MyClass result = first + second;
Here is the MSDN article on operators and overriding in C#: http://msdn.microsoft.com/en-us/library/s53ehcz3(loband).aspx

Categories