how to use interface and purpose of casting? - c#

i have used interface in both cases. is it my first case use interface ??
here is the my interface and class
interface IAddition {
int Add();
}
interface IMultiplication {
int Multiplication();
}
it is my class
public class Calculation : IAddition, IMultiplication {
int x, y;
public Calculation(int x, int y) {
this.x = x;
this.y = y;
}
public int Add() {
return (x + y);
}
public int Multiplication() {
return (x * y);
}
}
1st case is this
class Program {
static void Main(string[] args) {
Calculation cal = new Calculation(20, 30);
Console.WriteLine("Sum is= " + cal.Add());
Console.WriteLine("Multiplication is= " + cal.Multiplication());
Console.ReadKey();
}
}
And 2nd case is this
class Program {
static void Main(string[] args) {
Calculation cal = new Calculation(20, 30);
IAddition add = (IAddition)cal;
IMultiplication mul = (IMultiplication)cal;
Console.WriteLine("Sum is= " + add.Add());
Console.WriteLine("Multiplication is= " + mul.Multiplication());
Console.ReadKey();
}
}
What is the purpose of these 2 lines ??? here what is the purpose of casting ?? Although 1st case have same output
IAddition add = (IAddition)cal;
IMultiplication mul = (IMultiplication)cal;

Only the second case programs to IAddition and IMultiplication interfaces. The first case would work even if the Calculation class did not implement IAddition and IMultiplication.
what is the purpose of casting?
Note that since you declare variables with an explicit interface type, you can safely drop the casts in the declarations of mul and add:
IAddition add = cal;
IMultiplication mul = cal;
You could also rewrite your declarations with implicit type declaration:
var add = (IAddition)cal;
var mul = (IMultiplication)cal;
What is the purpose of these 2 lines?
These lines declare two variables using the interface type implemented by Calculation. They make no practical difference in this example, but generally you could use add and mul to be specific about the level of abstraction to which you program. For example, IAddition add tells the readers of your program that you do not need to use any aspects of cal except these related to addition.

The other answers cover the given example code, but it's worthwhile to add that the rules are different for explicit interface implementation.
For example, if the example class was implemented as follows:
public class Calculation : IAddition, IMultiplication {
int x, y;
public Calculation(int x, int y) {
this.x = x;
this.y = y;
}
public int IAddition.Add() {
return (x + y);
}
public int IMultiplication.Multiplication() {
return (x * y);
}
}
then the cast is required. For example:
Calculation cal = new Calculation(10, 10);
cal.Multiplication(); // this will cause a compiler error
((IMultiplication)cal).Multiplication(); // This is the required way to do it
For more information see this article on MSDN

In this case, the purpose is just to show you how you can cast types. It doesn't make a difference in how the code works, but you can see that if you were to try add.Multiplication(), the compiler would tell you that's not allowed.
In a simple example like this, there's no reason to cast and declare variables like this. However, in larger applications, the Interface Segregation Principle helps us to avoid tight coupling of different pieces of code. For example, you could write a method like this:
int SumAll(IAddition adder, params int[] values)
{
int sum = 0;
foreach(int n in values)
{
sum = adder.Add(sum, values[i]);
}
return sum;
}
The above method would work just fine if you pass it a Calculator, but it doesn't have to use a Calculator. Since you know you don't need to multiply anything in this method, this limits your dependencies to the things that you actually need. You might in the future find it useful to implement an Add method with a ceiling, for example, that never allows numbers to go above a certain number, no matter how many things get added. Passing that IAddition object into SumAll would have a different effect, and you wouldn't have to create a different SumAll method to accommodate this need.
Console.WriteLine(SumAll(new Calculator(), 1, 2)); // 3
Console.WriteLine(SumAll(new Calculator(), 1, 2, 3)); // 6
Console.WriteLine(SumAll(new AdderWithMax(4), 1, 2)); // 3
Console.WriteLine(SumAll(new AdderWithMax(4), 1, 2, 3)); // 4
In general, people find that by separating interfaces intelligently, they're able to write code that's easier to test and less likely to require as much work when changes are made in the future--in other words, more maintainable code.
Oh, and by the way, the explicit cast isn't actually necessary, so this would also have the same effect:
IAddition add = cal;
or:
var add = (IAddition)cal;

how to use interface
There are many ways to use an inteface, from implementation to type-checking.
// Definition of interface or sometimes referred to as "Contract"
// Implementing classes must define these methods and properties
public interface IMyInterface
{
void MyMethod();
int MyProperty { get; }
}
// Implementation or sometimes referred to as "Concrete type"
public class MyClass : IMyInterface
{
public void MyMethod();
public int MyProperty { get; set; }
}
// Compile time type checking:
public void MyMethod<T>(T value)
where T : IMyInterface
{ }
// Runtime checking
public void MyMethod(object someobject)
{
var myinterface = someobject as IMyInterface;
if (myinterface != null)
{
//someobject implements IMyInterface so I can do things with it
someobject.MyMethod();
}
}
and purpose of casting?
The purpose of casting is has many uses. I'll mostly be demonstrating use the as keyword because it provides type-safety for the run-time.
You can use it to validate a type implements an interface at run-time:
public MyMethod(object obj)
{
var calc = obj as ICalc;
if (calc != null)
{
calc.Calculate();
}
}
This can be improved:
public void MyMethod(ICalc calc)
{
calc.Calculate();
}
Using generics and compile time type safety (I think it's important to show).
public void MyMethod<TObject>(TObject calc)
where TObject : ICalc
{
calc.Calculate();
}
is it my first case use interface ??
I'm not sure what this means, I think what you are trying to say is
Am I required to use the interface by casting it?
No you are not. Lets take a look at these two classes:
public class Calculation1 : IAddition, IMultiplication {
public int Add() { //... ignoring implemenetation
}
public int Multiplication() { //... ignoring implemenetation
}
}
public class Calculation2 {
public int Add() {//... ignoring implemenetation
}
public int Multiplication() {//... ignoring implemenetation
}
}
Both of the classes implement the same methods so these are valid:
var one = new Calculation1();
one.Add();
var two = new Calculation1();
two.Add();
However because the first one implements an interface and the second one does not, you can pass the first object to methods that do not need to know the concrete type.
public void MethodNeedsToAdd(IAddition addCalculator)
{
if (addCalculator != null)
{
addCalculator.Add();
}
}
MethodNeedsToAdd(one); // Valid
MethodNeedsToAdd(two); // Invalid
Even though you and I can clearly see they both can "Add" the second class two does not implement the interface.

It's all about concealing complexity. When you do this cast ...
IAddition add = (IAddition)cal;
You can then handle this add item as if all it can do is implement your IAddition interface. That might prove convenient if you were implementing a complex system.
For example, you might define an IGetNextItem interface. Then, you might choose to implement that interface in a class which fetched an item from a DBMS, and another which generated a random fake item. You would be able to cast either object, and then pass it to some software which consumed those items, without needing to tell the consuming software exactly how the fetching of items actually works.

You don't need the cast. You can say...
IAddition add = cal;
However, the point of that is you are creating an object of any type that implements the IAddition interface.

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);

Calculate absolute value of numbers using Generic class

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); }
}

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>

Why does C# tease with structural typing when it absolutely knows it doesn't have it?

I was surprised to see today that this was possible, but I worry this must be discussed before.
public interface ICanAdd
{
int Add(int x, int y);
}
// Note that MyAdder does NOT implement ICanAdd,
// but it does define an Add method like the one in ICanAdd:
public class MyAdder
{
public int Add(int x, int y)
{
return x + y;
}
}
public class Program
{
void Main()
{
var myAdder = new MyAdder();
var iCanAdd = (ICanAdd)myAdder; //compiles, but for what sake?
int sum = iCanAdd.Add(2, 2); //na, not game for it, cast had already failed
}
}
The compiler will (rightly?) tell me that an explicit cast exists in the above situation. I was all thrilled to sense structural typing in there, but no run time it fails. So when is C# being ever helpful here? Any scenarios such casting would work? Whatever it is, I'm sure compiler beforehand knows myAdder is not ICanAdd, well technically.
C# allows an explicit conversion from a class to an interface (even if the class doesn't implement that interface), because for all the compiler knows, a reference to a certain type might actually (the uncertainty is why it's an explicit rather than implicit conversion) be an instance of a derived type that does implement the interface. Extending your example, suppose you have:
public class DerivedAdder : MyAdder, ICanAdd
{
int ICanAdd.Add(int x, int y)
{
return base.Add(x, y);
}
}
...
MyAdder myAdder = new DerivedAdder();
var iCanAdd = (ICanAdd)myAdder; // Valid in this case
int sum = iCanAdd.Add(2, 2); // sum = 4
If you check section 6.2.4 of the C# Specification, you'll see that if you mark your MyAdder class as sealed, the compiler will actually complain, because then it will know for sure that no conversion is possible, since no derived type could exist. But as long as it can't eliminate every last shred of doubt, it'll allow an explicit conversion.
Casting class to interface is allowed by C# language specification. But for example if ICanAdd was a class - compilation would fail

Understanding .Net Generics - Bank Domain

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.

Categories