I have a .Net library. say with 2 public functions. say one is Summmator which takes 2 arguments and does A+B. Another function simpleMultiplicator which takes 2 arguments: a number to multiplicate and count of times it should be multiplicated. A simpleMultiplicator function when called uses Summmator function. So it is my library. It is compiled into dll for .net4. In my programm I want to extend or modify Summator function so that when I call simpleMultiplicator it would use my modification of original Summator function. Is it possible in .net4, how to do it?
(C#, visual-C++)
It depends on how you design your classes. You state that your library exports two public functions, but they need to be defined on a class either as static or instance method, so you can make use of object-orientated principles like inheritance or polymorphism to achieve what you want.
Here is an example using inheritance:
namespace MyLibrary
{
public class MyMath
{
// Be aware of the virtual keyword which enables overriding the method
public virtual int Summmator(int a, int b)
{
return a + b;
}
public int SimpleMultiplicator(int a, int b)
{
int result = 0;
for (int i = 0; i < b; i++)
{
result = Summmator(result, a);
}
}
}
}
namespace MyProgram
{
using MyLibrary;
public class MyExtendedMath : MyMath
{
public override int Summmator(int a, int b)
{
return a + 2 * b;
}
}
public static class Program
{
public static void Main()
{
MyMath math = new MyExtendedMath();
int result = math.SimpleMultiplicator(2, 3);
Console.WriteLine(result);
}
}
}
Another way is to use polymorphism:
namespace MyLibrary
{
public interface ISummmator
{
int Summmator(int a, int b);
}
public class Summmator : ISummator
{
public int Summmator(int a, int b)
{
return a + b;
}
}
public static class MyMath
{
public static int SimpleMultiplicator(int a, int b, ISummmator summmator)
{
int result = 0;
for (int i = 0; i < b; i++)
{
result = summmator.Summmator(result, a);
}
}
}
}
namespace MyProgram
{
using MyLibrary;
public class MySummmator : ISummmator
{
public int Summmator(int a, int b)
{
return a + 2 * b;
}
}
public static class Program
{
public static void Main()
{
int result = MyMath.SimpleMultiplicator(2, 3, new MySummmator());
Console.WriteLine(result);
}
}
}
Best Regards,
Oliver Hanappi
First, I'd objectify these things. So you have a Summator which provides a sum function, and a SimpleMultiplicator which provides a multiply function. Then, you add the Summator to the SimpleMultiplicator in the default case. For example,
class SimpleMultiplicator
{
public SimpleMultiplicator()
{
this.summator = new Summator();
}
public int Mult(int a, int b)
{
// ...
this.summator.sum(something, somethingelse);
// etc
}
Then you create another constructor where you can override the default Summator:
public SimpleMultiplicator(Summator summator)
{
this.summator = summator;
}
So if you want to change the summation function, you create a new Summator-based class, override its sum() method and pass it on to the SimpleMultiplicator constructur.
Related
I have two constructors which feed values to readonly fields.
public class Sample
{
public Sample(string theIntAsString)
{
int i = int.Parse(theIntAsString);
_intField = i;
}
public Sample(int theInt) => _intField = theInt;
public int IntProperty => _intField;
private readonly int _intField;
}
One constructor receives the values directly, and the other does some calculation and obtains the values, then sets the fields.
Now here's the catch:
I don't want to duplicate the
setting code. In this case, just one
field is set but of course there may
well be more than one.
To make the fields readonly, I need
to set them from the constructor, so
I can't "extract" the shared code to
a utility function.
I don't know how to call one
constructor from another.
Any ideas?
Like this:
public Sample(string str) : this(int.Parse(str)) { }
If what you want can't be achieved satisfactorily without having the initialization in its own method (e.g. because you want to do too much before the initialization code, or wrap it in a try-finally, or whatever) you can have any or all constructors pass the readonly variables by reference to an initialization routine, which will then be able to manipulate them at will.
public class Sample
{
private readonly int _intField;
public int IntProperty => _intField;
private void setupStuff(ref int intField, int newValue) => intField = newValue;
public Sample(string theIntAsString)
{
int i = int.Parse(theIntAsString);
setupStuff(ref _intField,i);
}
public Sample(int theInt) => setupStuff(ref _intField, theInt);
}
Before the body of the constructor, use either:
: base (parameters)
: this (parameters)
Example:
public class People: User
{
public People (int EmpID) : base (EmpID)
{
// Add more statements here.
}
}
I am improving upon supercat's answer. I guess the following can also be done:
class Sample
{
private readonly int _intField;
public int IntProperty
{
get { return _intField; }
}
void setupStuff(ref int intField, int newValue)
{
//Do some stuff here based upon the necessary initialized variables.
intField = newValue;
}
public Sample(string theIntAsString, bool? doStuff = true)
{
//Initialization of some necessary variables.
//==========================================
int i = int.Parse(theIntAsString);
// ................
// .......................
//==========================================
if (!doStuff.HasValue || doStuff.Value == true)
setupStuff(ref _intField,i);
}
public Sample(int theInt): this(theInt, false) //"false" param to avoid setupStuff() being called two times
{
setupStuff(ref _intField, theInt);
}
}
Here is an example that calls another constructor, then checks on the property it has set.
public SomeClass(int i)
{
I = i;
}
public SomeClass(SomeOtherClass soc)
: this(soc.J)
{
if (I==0)
{
I = DoSomethingHere();
}
}
Yeah, you can call other method before of the call base or this!
public class MyException : Exception
{
public MyException(int number) : base(ConvertToString(number))
{
}
private static string ConvertToString(int number)
{
return number.toString()
}
}
Constructor chaining i.e you can use "Base" for Is a relationship and "This" you can use for same class, when you want call multiple Constructor in single call.
class BaseClass
{
public BaseClass():this(10)
{
}
public BaseClass(int val)
{
}
}
class Program
{
static void Main(string[] args)
{
new BaseClass();
ReadLine();
}
}
When you inherit a class from a base class, you can invoke the base class constructor by instantiating the derived class
class sample
{
public int x;
public sample(int value)
{
x = value;
}
}
class der : sample
{
public int a;
public int b;
public der(int value1,int value2) : base(50)
{
a = value1;
b = value2;
}
}
class run
{
public static void Main(string[] args)
{
der obj = new der(10,20);
System.Console.WriteLine(obj.x);
System.Console.WriteLine(obj.a);
System.Console.WriteLine(obj.b);
}
}
Output of the sample program is
50 10 20
You can also use this keyword to invoke a constructor from another constructor
class sample
{
public int x;
public sample(int value)
{
x = value;
}
public sample(sample obj) : this(obj.x)
{
}
}
class run
{
public static void Main(string[] args)
{
sample s = new sample(20);
sample ss = new sample(s);
System.Console.WriteLine(ss.x);
}
}
The output of this sample program is
20
Error handling and making your code reusable is key. I added string to int validation and it is possible to add other types if needed. Solving this problem with a more reusable solution could be this:
public class Sample
{
public Sample(object inputToInt)
{
_intField = objectToInt(inputToInt);
}
public int IntProperty => _intField;
private readonly int _intField;
}
public static int objectToInt(object inputToInt)
{
switch (inputToInt)
{
case int inputInt:
return inputInt;
break;
case string inputString:
if (!int.TryParse(inputString, out int parsedInt))
{
throw new InvalidParameterException($"The input {inputString} could not be parsed to int");
}
return parsedInt;
default:
throw new InvalidParameterException($"Constructor do not support {inputToInt.GetType().Name}");
break;
}
}
Please, please, and pretty please do not try this at home, or work, or anywhere really.
This is a way solve to a very very specific problem, and I hope you will not have that.
I'm posting this since it is technically an answer, and another perspective to look at it.
I repeat, do not use it under any condition. Code is to run with LINQPad.
void Main()
{
(new A(1)).Dump();
(new B(2, -1)).Dump();
var b2 = new B(2, -1);
b2.Increment();
b2.Dump();
}
class A
{
public readonly int I = 0;
public A(int i)
{
I = i;
}
}
class B: A
{
public int J;
public B(int i, int j): base(i)
{
J = j;
}
public B(int i, bool wtf): base(i)
{
}
public void Increment()
{
int i = I + 1;
var t = typeof(B).BaseType;
var ctor = t.GetConstructors().First();
ctor.Invoke(this, new object[] { i });
}
}
Since constructor is a method, you can call it with reflection. Now you either think with portals, or visualize a picture of a can of worms. sorry about this.
In my case, I had a main constructor that used an OracleDataReader as an argument, but I wanted to use different query to create the instance:
I had this code:
public Subscriber(OracleDataReader contractReader)
{
this.contract = Convert.ToString(contractReader["contract"]);
this.customerGroup = Convert.ToString(contractReader["customerGroup"]);
this.subGroup = Convert.ToString(contractReader["customerSubGroup"]);
this.pricingPlan= Convert.ToString(contractReader["pricingPlan"]);
this.items = new Dictionary<string, Member>();
this.status = 0;
}
So I created the following constructor:
public Subscriber(string contract, string customerGroup) : this(getSubReader(contract, customerGroup))
{ }
and this method:
private static OracleDataReader getSubReader(string contract, string customerGroup)
{
cmdSubscriber.Parameters[":contract"].Value = contract + "%";
cmdSubscriber.Parameters[":customerGroup"].Value = customerGroup+ "%";
return cmdSubscriber.ExecuteReader();
}
notes: a statically defined cmdSubscriber is defined elsewhere in the code; My main constructor has been simplified for this illustration.
In case you need to run something before calling another constructor not after.
public class Sample
{
static int preprocess(string theIntAsString)
{
return preprocess(int.Parse(theIntAsString));
}
static int preprocess(int theIntNeedRounding)
{
return theIntNeedRounding/100;
}
public Sample(string theIntAsString)
{
_intField = preprocess(theIntAsString)
}
public Sample(int theIntNeedRounding)
{
_intField = preprocess(theIntNeedRounding)
}
public int IntProperty => _intField;
private readonly int _intField;
}
And ValueTuple can be very helpful if you need to set more than one field.
NOTE: most of the solutions above does not work for structs.
Unfortunately initializing struct fields in a method called by a constructor is not recognized by the compiler and will lead to 2 errors:
in the constructor: Field xxxx must be fully assigned...
in the method, if you have readonly fields: a read-only field cannot be assigned except in a constructor.
These can be really frustrating for example when you just need to do simple check to decide on which constructor to orient your call to.
I'm learning about delegates. This is example code (first) from a LinkedIn tutorial on C#. I am unable to identify the advantage and purpose of using the delegate. Its unclear what the reasons are we would not call the function directly. I retyped my own code (second) that appears to give a similar result.
namespace Delegates1._10._2018
{
public delegate string MyDelegate(int arg1, int arg2);
internal class Program
{
static string func1(int a, int b)
{
return (a + b).ToString();
}
static string func2(int a, int b)
{
return (a * b).ToString();
}
static void Main(string[] args)
{
MyDelegate f = func1;
Console.WriteLine("The number is: " + f(10,20));
f = func2;
Console.WriteLine("The number is: " + f(10,20));
}
}
}
internal class Program
{
public static int func1(int a, int b)
{
return (a + b);
}
public static int func2(int a, int b)
{
return (a * b);
}
static void Main(string[] args)
{
Console.WriteLine("The number is: " + func1(10, 20));
Console.WriteLine("The number is: " + func2(10, 20));
}
}
The number is: 30
The number is: 200
The delegate is just declaring the shape of a method (public delegate string MyDelegate(int arg1, int arg2);. You can change which method is called as shown in your first Main method. This is a contrived example, which doesn't have much benefit as it doesn't deal with external data or input to manipulate the behavior.
The example is bad!. Let me try to explain:
We have a Class Car, the Car does not know how to drive itself, the Person sitting in the Car, knows how to drive it. So the Car Asks to the Person (Delegate) Drive me!
public delegate int DriveMeWithSpeed(int maxForceOnPedal);
public class Car
{
DriveMeWithSpeed speedy;
public Car(DriveMeWithSpeed YourSpeed)
{
speedy = YourSpeed;
}
public void Drive()
{
if (speedy != null) speedy(100);
}
}
public class Person
{
public int IDrive(int PedalForce)
{
return 40;
}
}
public static void Main(string[] args)
{
Person Me = new Person();
Car myCar = new Car(Me.IDrive);
myCar.Drive();
}
So main concept is that the class itself does not always know the functionality of a function so it delegates this to the class who knows what to do.
I have read a lot of things about how marker interfaces are bad (or not, it does not seem so clear).
I do not really understand how Marker Attributes work, and I have created a small example to illustrate my issues:
I have an interface to define Robot, and an other one to define Ninja. It turns out that it exists a classFoo that can multiply stuff, but only with the help of someone which is both a RobotAND a Ninja.
using System;
public class Program
{
public static void Main()
{
IRobotNinja robotNinja = new RobotNinjaAlways10();
Foo foo = new Foo();
Console.WriteLine(foo.Multiply(1, 1, robotNinja));
}
}
public class Foo
{
public int Multiply(int leftOperand, int rightOperand, IRobotNinja robotNinja)
{
return leftOperand * rightOperand * robotNinja.availableShuriken * robotNinja.batteryLevel;
}
}
public interface IRobot
{
int batteryLevel
{
get;
}
}
public interface INinja
{
int availableShuriken
{
get;
}
}
public interface IRobotNinja : IRobot, INinja
{
}
public class RobotNinjaAlways10 : IRobotNinja
{
public int batteryLevel
{
get
{
return 10;
}
}
public int availableShuriken
{
get
{
return 10;
}
}
}
It is my understanding that IRobotNinja is a marker class: it has no members.
How can I get the same thing (and in particular, ensuring at compile time that only a Robot/Ninja will help with the Multiply?
To avoid creating another interface, you can make Multiply generic with constraints:
public class Foo
{
public int Multiply<T>(int leftOperand, int rightOperand, T robotNinja)
where T : IRobot, INinja
{
return leftOperand * rightOperand * robotNinja.availableShuriken
* robotNinja.batteryLevel;
}
}
Idea is to have extension method that extend my functionality.
So instead of having something like this:
return Add(Add(storage.GetFirst(), 3), 7);
I want have something like this:
return storage.GetFirst().Add(3).Add(7);
Problem with extension methods is that they have to be static in static class.
This is simplify example of what I want to do.
public class Storage
{
public int GetFirst()
{
return 100;
}
public int GetAll(int x, int y)
{
// ...
return x + y;
}
}
public abstract class MyBase
{
protected Storage storage;
protected MyBase()
{
storage = new Storage();
}
public int Add(int what, int howMuch)
{
return storage.GetAll(what, howMuch);
}
}
public class MyClass : MyBase
{
public int method1()
{
return Add(Add(storage.GetFirst(), 3), 7);
//I want have something like this:
// return storage.GetFirst().Add(3).Add(7);
}
}
Off course classes Storage, MyBase and MyClass must not be static. Logic is simplify to have clean and simple example so relation between classes must stay same.
What I want to do is to make Add method to be extension method, but leave everything else "more less same".
Is this possible to do and how?
An alternative solution would be to make your Storage class actually store something:
public class Storage
{
private int currentValue;
public Storage GetFirst()
{
this.currentValue = 100;
return this;
}
public Storage Add(int toAdd)
{
this.currentValue += toAdd;
return this;
}
public int GetResult()
{
return this.currentValue;
}
}
This way your call would be:
int result = new Storage().GetFirst().Add(3).Add(5).GetResult();
Have one static class for extensions and use something like:
internal static T Map<T> (this int source, Func<int, int, T> function, int extraParam) {
function (source, extraParam);
}
Then you can make your add method something like:
storage.GetFirst ().Map (Add, 3).Map (Add, 7);
Without modifying any of your code, it is possible to achieve what you're trying to do. But your current design makes it hard to do. You should have some storage in Storage class. There is no storage in Storage class despite of its name.
public class StorageValue
{
public StorageValue(Storage storage)
{
this.Storage = storage;
}
public StorageValue(Storage storage, int value)
{
this.Storage = storage;
this.Value = value;
}
public Storage Storage { get; private set; }
public int Value { get; private set; }
public StorageValue GetFirst()
{
return new StorageValue(Storage, Storage.GetFirst());
}
public StorageValue Add(int value)
{
return new StorageValue(Storage, Storage.GetAll(Value, value));
}
public int GetValue()
{
return Value;
}
}
public static class StorageExtensions
{
public static StorageValue ToStorageValue(this Storage storage)
{
return new StorageValue(storage);
}
}
Which these couple of classes, you can call the methods like this
public class MyClass : MyBase
{
public int method1()
{
return storage
.ToStorageValue()
.GetFirst()
.Add(3)
.Add(7)
.GetValue();
}
}
If you want Add, GetFirst to be the extension methods, you may do it now with StorageValue class. But it makes more sense to be in StorageValue class itself.
That said, # Manuel Zelenka's answer is similar to mine which looks better. You may adapt any of them.
First of all, take a look at my below code:
class A
{
public static int Flag()
{
return 0;// set initial value=0
}
B b= new B();
public void afunc()
{
b.bfunc();
}
}
And class B recieves and sends static variable:
class B
{
A a= new A();
int flag= a.Flag();
public void bfunc()
{
if(flag==0)
{
flag=1;//???? is this wrong???
//do some thing
}
}
}
Class A send to B a static variable with initial value=0; then class A call bfunc from class B. In bfunc() I set flag=1. I'm a new to C#. Can you share me how class A recieves back flag=1 sended by class B. I mean which syntax?
a few things are wrong here
Flag is a method on A, so you cannot change its "value"
Flag is static therefore it does not have an instance which is what I think you want
I suspect you want Flag to be a property of A
public int Flag{get;set;}
You are making new instances of A and B, which may be correct for you but be weary this means you are not referencing existing instances
You have two options
A
this.Flag = b.bFunc();
public int bFunc()
.... return 1;
B
public void bFunc()
... a.Flag = 1;
If you really want static variable then
public static int Flag = 0;
A.Flag = x
Were is no static variable here, you only have a static function int Flag(). To get value of a flag in class A, you must return this value from function bfunc() like this:
public int bfunc()
{
if(flag==0)
{
flag=1;
return flag;
}
}
I don't know if I understood you properly because there are many things wrong with your code. Flag should be a property instead of a method so you can store your value. The way you used it was just tossing out a zero.
First, your two classes. Keep in mind that usually properties should be used as accesssors to private fields, but let's do it the simplest way.
class A
{
public static int Flag = 0;
}
class B
{
public void bfunc()
{
if (A.Flag == 0)
{
A.Flag = 1;
}
}
}
Then use them as follows to change Flag's value.
B bObject = new B();
bObject.bfunc();
// A.Flag is now 1.
Note that bfunc() will change Flag's value to 1 only if it was 0 before.