C# - Example of Extension Method - c#

Please could someone provide me with a simple extension method that for example squares a number.
I have drawn up so pseudo code:
class Program
int = x
---------------------
public static int square (this int x)
return x * square

public static class NumberExtensions
{
public static int Square(this int n)
{
return n*n;
}
}
Now you can say:
int number=5.Square();

Here is how you would write the method:
public static class ExtnMethods
{
public static int Square(this int x)
{
return x * x;
}
}
Some important things to note about the above code:
The class must be static and non-abstract
The parameter this int x specifies that the method acts on an int
You would use it like so:
Console.WriteLine(5.Square());
// prints 25

public static class SomeClass {
public static int Square(this int x) {
return x * x;
}
}

The extension method:
static class MathExtensions {
public static Int32 Square(this Int32 x) {
return x*x;
}
}
How to use it:
var x = 5;
var xSquared = x.Square();

In this example I tried to show you how use multiple Extension method in a single expression.
class Program
{
static void Main(string[] args)
{
int x = 13;
var ans = x.Cube().Half().Square();
Console.WriteLine(ans);
}
}
static class IntExtensions
{
public static int Half(this int source)
{
return source / 2;
}
public static int Cube(this int source)
{
return (int)Math.Pow(source, 3);
}
public static int Square(this int source)
{
return (int)Math.Pow(source, 2);
}
}

Related

My delegate type isn't working "Method name expected"

I tried this:
class Program
{
public delegate int add(int x, int y);
public class ff
{
public static int addNumbers(int x, int y)
{
return x + y;
}
public static int substractNumbers(int x, int y)
{
return x - y;
}
static void Main(string[] args)
{
Delegate delegare = new add(ff.addNumbers);
Console.WriteLine(delegare(3,4));
}
}
I don't see why I'm getting this error"Method name expected".
When I use a delegate with a void function it works.
Can someone help me?
The type of your delegare variable is just Delegate. That could refer to any delegate. In order to invoke a delegate (in the normal way), you should have an expression of the appropriate type.
After fixing the naming conventions and removing the unnecessary nested class - and demonstrating a method group conversion - your code looks like this:
using System;
public delegate int Int32Operation(int x, int y);
class Program
{
public static int AddNumbers(int x, int y)
{
return x + y;
}
public static int SubtractNumbers(int x, int y)
{
return x - y;
}
static void Main(string[] args)
{
Int32Operation op = new Int32Operation(AddNumbers);
Console.WriteLine(op(3, 4)); // Prints 7
op = SubtractNumbers; // Method group conversion
Console.WriteLine(op(3, 4)); // Prints -1
}
}
You should try this out:
add delegare = new add(ff.addNumbers);
The type of your delegate should be add since you defined so.

C# - Passing Delegate as a parameter to a method

I am trying to get familiar with the concept of delegates in C#. I have created this console application so far:
Program.cs
using System;
namespace DelegatesTest
{
class Program
{
static void Main(string[] args)
{
ArithmeticOperation.ArOpDel additionDelegate = new ArithmeticOperation.ArOpDel(ArithmeticOperation.Addition);
Console.WriteLine(ArithmeticOperation.ConvertResultToString(additionDelegate(10, 5)));
Console.ReadKey();
}
}
}
ArithmeticOperation.cs
using System;
namespace DelegatesTest
{
public static class ArithmeticOperation
{
public delegate int ArOpDel(int x, int y);
public static string ConvertResultToString(ArOpDel del)
{
string result = String.Format("The result of the {0} operation is {1}", del.Method.Name, del.ToString());
return result;
}
public static int Addition(int x, int y)
{
return x + y;
}
public static int Subtraction(int x, int y)
{
return x - y;
}
public static int Multiplication(int x, int y)
{
return x * y;
}
public static int Division(int x, int y)
{
return x / y;
}
}
}
As you can see from the code, I am using a static class called ArithmeticOperation.cs to perform some arithmetic operations. The ConvertResultToString method takes one of the arithmetic operations methods as a parameter in order to display the result elegantly as a string.
Unfortunately, my code does not compile. It is giving me the following error:
Argument '1': cannot convert from 'int' to 'DelegatesTest.ArithmeticOperation.ArOpDel'
The error is being given on this line:
Console.WriteLine(ArithmeticOperation.ConvertResultToString(additionDelegate(10, 5)));
Can you please help me solve this problem as I am not very experienced with delegates? In fact, I have created this application to learn about delegates.
The additionDelegate(10, 5) will return int by doing arithmetic operation, it will not return deleagate that's the reason of compilation error.
Console.WriteLine(ArithmeticOperation.ConvertResultToString(additionDelegate(10, 5)));
You are not passing the delegate here. You are calling it, which results in an int.
This would pass the delegate:
Console.WriteLine(ArithmeticOperation.ConvertResultToString(additionDelegate));
You would need to actually call the delegate somewhere though.
when you do this
Console.WriteLine(ArithmeticOperation.ConvertResultToString(additionDelegate(10, 5)));
you are forcing the compiler to execute the method and return the result to pass it as an argument which in this case it's an int while the ConvertResultTostring expect a delegate
here how you can get it work without using generic
class Program
{
static void Main(string[] args)
{
ArithmeticOperation.ArOpDel additionDelegate = ArithmeticOperation.Addition;
Console.WriteLine(ArithmeticOperation.ConvertResultToString(additionDelegate,5,6));
Console.ReadKey();
}
}
public static class ArithmeticOperation
{
public delegate int ArOpDel(int x, int y);
public static string ConvertResultToString(ArOpDel del,int x, int y )
{
string result = String.Format("The result of the {0} operation is {1}", del.Method.Name, del(x,y).ToString());
return result;
}
public static int Addition(int x, int y)
{
return x + y;
}
public static int Subtraction(int x, int y)
{
return x - y;
}
public static int Multiplication(int x, int y)
{
return x * y;
}
public static int Division(int x, int y)
{
return x / y;
}
}
additionDelegate(10, 5) is an invocation of additionDelegate which actually is an Addition function. So, the result is an integer.
In order to pass a delegate you should pass additionDelegate itself instead of additionDelegate(10, 5). But, in this case, the result of the operation will not be available in ConvertResultToString unless you invoke it there.
public static string ConvertResultToString(ArOpDel del)
{
string result = String.Format("The result of the {0} operation is {1}", del.Method.Name, del(10, 5).ToString());
return result;
}
...
Console.WriteLine(ArithmeticOperation.ConvertResultToString(additionDelegate));
additionDelegate(10, 5) means invoke the delegate,the result is an int type which does not match the ConvertResultToString method stub.
you need change
Console.WriteLine(ArithmeticOperation.ConvertResultToString(additionDelegate(10, 5)))
to
Console.WriteLine(ArithmeticOperation.ConvertResultToString(additionDelegate))
and change
string result = String.Format("The result of the {0} operation is {1}", del.Method.Name, del.ToString());
to
string result = String.Format("The result of the {0} operation is {1}", del.Method.Name, del(10,5).ToString());

How to define a fix value to a variable?

Title of my question is quite different from my question. I am sorry for that because i don't know what should be title for this question.
Suppose i have one class let's say "ClassA"
Class ClassA
{
int x=5;
int y=6;
int z=7;
static public int sum(int a,int b)
{
return (a+b);
}
}
now i need some logic by which i can use sum() like following in another class
int c = ClassA.sum(x,y);
int d = ClassA.sum(x,z);
here i don't need to declare "x","y" and "z" variable. It must be a consider a value that is defined in ClassA.
My question can be silly but just help me.
What should i do ????
You can declare x, y, and z as const:
class ClassA
{
public const int x=5;
public const int y=6;
public const int z=7;
static public int sum(int a,int b)
{
return (a+b);
}
}
Then do:
int c = ClassA.sum(ClassA.x,ClassA.y);
You can pass an instance of an object to a static method, it can invoke instance members on that object.
class ClassA
{
int x=5;
int y=6;
int z=7;
static public int sum(ClassA obj)
{
return (obj.x+ obj.y);
}
}
In other class create instance of class ClassA and pass this object to static method
ClassA objA = new ClassA();
int c = ClassA.sum(objA);
Check if the following code fits your requirement.
Create an enum as:
public enum MyEnum
{
x,y,z
}
The classA code will be:
class ClassA
{
static int x = 5;
static int y = 6;
static int z = 7;
static public int sum(MyEnum enum1, MyEnum enum2)
{
int a = 0;
int b = 0;
switch (enum1)
{
case MyEnum.x:
a = x;
break;
case MyEnum.y:
a = y;
break;
case MyEnum.z:
a = z;
break;
default:
break;
}
switch (enum2)
{
case MyEnum.x:
b = x;
break;
case MyEnum.y:
b = y;
break;
case MyEnum.z:
b = z;
break;
default:
break;
}
return (a + b);
}
}
I have set x,y,z as static because your method is static and you cannot access instance members in static method. Or you can replace static with const while declaring variable x,y,z.
Hope this helps.

Multicast delegate always does the last operation

So I have the following the code:
namespace ConsoleApplication1
{
public delegate int Transformer(int x);
class Test
{
public static void Transform(int[] values, Transformer t)
{
for (int i = 0; i < values.Length; i++)
{
values[i] = t(values[i]);
}
}
static int Square(int x)
{
return x * x;
}
static int Minus(int x)
{
return x - 1;
}
static void Main()
{
int[] values = { 1, 2, 3 };
Transformer t = Test.Minus;
t += Test.Square;
Test.Transform(values, t);
foreach (int i in values)
{
Console.Write(i + " ");
}
}
}
}
Why is it always does only the last operation to the array(Square in my case). What should I need to change so it will do both Minus and Square ?
Multicast delegates always return the value of the last delegate in chain. Since you don't modify values in Test.Minus and Test.Square, but return new values, only latter is applied. The simplest way to fix this would to make your transformers take values by reference and modify them. e.g:
namespace ConsoleApplication1
{
public delegate void Transformer(ref int x);
class Test
{
public static void Transform(int[] values, Transformer t)
{
for (int i = 0; i < values.Length; i++)
{
t(ref values[i]);
}
}
static void Square(ref int x)
{
x = x * x;
}
static void Minus(ref int x)
{
x = x - 1;
}
static void Main()
{
int[] values = { 1, 2, 3 };
Transformer t = Test.Minus;
t += Test.Square;
Test.Transform(values, t);
foreach (int i in values)
{
Console.Write(i + " ");
}
}
}
}
Because the result is not chained through all the delegates
the code becomes the equivalent of
Minus(1);
return Square(1);
change the code to alter the variable in place.
public delegate void Transformer(ref int x);
public static void Transform(int[] values, Transformer t)
{
for (int i = 0; i < values.Length; i++)
{
t(ref values[i]);
}
}
static void Square(ref int x)
{
x*= x;
}
static void Minus(ref int x)
{
x--;
}
A far better solution would be to use a linq agregate because you could transform the solution without affecting the source.
public static int[] Transform(int[] values, params Func<int,int>[] t){
return values.Select(v=>t.Aggregate(v,(x,f)=>f(x))).ToArray();
}
Then you can just call
values=Transform(values,new[] { Minus,Square });
or
int[] values = {1,2,3};
int[] result = Transform(values,Minus,Square);
After this call values!=result so source is unchanged

Why can't a delegate refer to a non-static method when used in a static method?

Why is it necessary to make a function STATIC while using delegates in C# ?
class Program
{
delegate int Fun (int a, int b);
static void Main(string[] args)
{
Fun F1 = new Fun(Add);
int Res= F1(2,3);
Console.WriteLine(Res);
}
**static public int Add(int a, int b)**
{
int result;
result = a + b;
return result;
}
}
It's not "necessary". But your Main method is static, so it can't call a non-static method. Try something like this (this isn't really a good way to do things—you really should create a new class, but it doesn't change your sample much):
class Program
{
delegate int Fun (int a, int b);
void Execute()
{
Fun F1 = new Fun(Add);
int Res= F1(2,3);
Console.WriteLine(Res);
}
static void Main(string[] args)
{
var program = new Program();
program.Execute();
}
int Add(int a, int b)
{
int result;
result = a + b;
return result;
}
}
Your function needs to be static because you're calling from a static method, Main. You can make the method non-static:
class Program
{
delegate int Fun (int a, int b);
static void Main(string[] args)
{
Program p = new Program(); // create instance of Program
Fun F1 = new Fun(p.Add); // now your non-static method can be referenced
int Res= F1(2,3);
Console.WriteLine(Res);
}
public int Add(int a, int b)
{
int result;
result = a + b;
return result;
}
}
In this case, because you aren't creating an instance of any class, the only alternative is a static function. Were you to instantiate an object of type Program, then you could use an instance method instead.
Delegates basically follow the same rules as methods. In the example provided your delegate must be static because you are calling it from a static method. In the same vein this will not work:
static void Main(string[] args)
{
int Res = Add(3, 4);
Console.WriteLine(Res);
}
public int Add(int a, int b)
{
int result;
result = a + b;
return result;
}
However if you moved things into a non static context like this:
class MyClass
{
public MyClass()
{
Fun F1 = new Fun(Add);
int Res = F1(2, 3);
Console.WriteLine(Res);
}
public int Add(int a, int b)
{
int result;
result = a + b;
return result;
}
}
You can have a delegate with a non-static method.
No need to create a static method to pass in delegate.
But the non static method should be declared in different class and have to be accessed with instance of that class.
DelegateName DN = new DelegateName ( instance of the class . Method Name)

Categories