Changing constructor parameter value structure map configuration - c#

I have a scenario similar to this:
public class A
{
private readonly string _test;
public A() : this("hello world")
{
}
public A(string test)
{
_test = test;
}
}
public class B
{
private readonly A _a;
public B(A a)
{
_a = a;
}
}
Now let's say that I have another class, in this class I am going to inject B but instead this time I want to pass a value for _test in class A
public class MainClass
{
private readonly B _b;
public MainClass()
{
// this is what I want as an injected result by structure map
_b = new B(new A("change me"));
}
}
so to do this in StructureMap, I have created the following Configuration
var testContainer = new Container(cg =>
{
cg.For<A>().Use<A>();
cg.For<B>().Use<B>().Ctor<A>("a").Is<A>().Ctor<string>("test").Is("change me");
});
var tsa = testContainer.GetInstance<A>();
var tsb = testContainer.GetInstance<B>();
But this doesn't seem to inject the string "change me" to the class A
How can I pass the string to Class A constructor for Class B only?

Your current approach defines two separate constructor parameters to construct type B: one of type A and name "a", and another with type string and name "test". Second one is not present and so is ignored.
Instead, you can do it like this:
cg.For<B>().Use<B>().Ctor<A>().IsSpecial(i => i.Type<A>().Ctor<string>().Is("change me"));

Related

Generic class and method binding with delegates(or not) for clean method expression

Lets say you have simple chained method but you are trying to access or set a value in a class property (internal/external doesnt matter). Using a Func seems to be working and finds the relation between generic class that is passed and access its properties correctly but i am not sure if its necessary.
Is there a way of setting the method variable cleanly as in Main method below since it is aware of the Generic class association without doing new Props().Property for example?
//sample console app
public class Props {
public string FirstProp = "lets say object";
public string SecondProp = "Pretend some other object";
}
public class Logic<T> where T : class, new()
{
private string outString { get; set; }
public Logic<T> GetPropertyValue(Func<T, object> propertySelector)
{
return this;
}
public Logic<T> GetLambda(Expression<Func<T, object>> propertySelector)
{
var breakpointCheck = propertySelector; //{x => x.SecondProp}
return this;
}
}
class Program
{
static void Main(string[] args)
{
var Test =
new Logic<Props>()
.GetPropertyValue(x => x.FirstProp) //dummy check
.GetLambda(x => x.SecondProp); //passed correctly {x => x.SecondProp}
var HowToGetThis =
new Logic<Props>()
.GetPropertyValue(FirstProp) // or GetPropertyValue(Props.FirstProp)
.GetLambda(x => x.SecondProp);
}
}

Create a constructor with parent class as parameter

I don't know how to define my question (probably already asked but didn't found it).
I want to create a constructor for a class B inherited from A taking a B object as parameter used to be a copy of it.
There can be something like this :
class B : A
{
public String NewField;
public B(A baseItem, String value)
{
// Create new B to be a copy of baseItem
???; // something like : this = baseItem
// Add new field
NewField = value;
}
}
Objective is to create an object B which is the exact copy of an A object with on filed more.
Use the base keyword to call the parent class constructor, giving your parent class instance as a parameter. Then create a copy constructor in your parent, and you're done.
class A
{
public A(A a)
{
// Copy your A class elements here
}
}
class B : A
{
public String NewField;
public B(A baseItem, String value)
: base(baseItem)
{
NewField = value;
}
}
You could implement a CopyProperties method, which will copy the properties values.
using System;
public class A
{
public string Filename {get; set;}
public virtual void CopyProperties(object copy)
{
((A)copy).Filename = this.Filename;
}
}
public class B : A
{
public int Number {get;set;}
public override void CopyProperties(object copy)
{
base.CopyProperties(copy);
((B)copy).Number = this.Number;
}
}
public class Program
{
public static void Main()
{
B b = new B { Filename = "readme.txt", Number = 42 };
B copy = new B();
b.CopyProperties(copy);
Console.WriteLine(copy.Filename);
Console.WriteLine(copy.Number);
}
}

Inner class (i.e. non-static nested class) in c#

Assume I've defined an interface with multiple properties, e.g.:
interface IFailable<T>
{
T Value { get; }
bool Success { get; }
}
and I want class Foo to expose multiple readonly instances of this, where IFailable properties are calculated from Foo's private non-static data, how would I do that in c#?
In Java its fairly intuitive.
Here's the best I came up in c#, based on https://stackoverflow.com/a/4770231/146567
First create a wrapper:
public class FailableDelegator<T> : IFailable<T>
{
public delegate T valueDelegate();
public delegate bool successDelegate();
private readonly valueDelegate valueHandler;
private readonly successDelegate successHandler;
public T Value { get { return valueHandler(); } }
public bool Success { get { return successHandler(); } }
public FailableDelegator(valueDelegate v, successDelegate s)
{
valueHandler = v;
successHandler = s;
}
}
Then use it to define the properties in Foo's constructor:
public class Foo
{
private double x = 3;
private double y = -9;
public readonly FailableDelegator<double> xPlusY;
public readonly FailableDelegator<double> sqrtY;
public Foo()
{
xPlusY = new FailableDelegator<double>(() => x + y, () => true);
sqrtY = new FailableDelegator<double>(() => Math.Sqrt(y), () => y>=0);
}
}
I had to put the definitions in Foo's constructor because I got error "cannot access non-static field in static context" if I attempted it directly on the field.
I'm not keen on this, because for less trivial examples you end up with a huge amount of code in Foo's constructor.

access property value of one class from another internal class in C#

how do i acces the property value from an internal class , see below?
namespace N1
{
public class ClassA
{
string var1 = null;
private ClassB b;
public ClassA()
{
var1 = "one";
b = new ClassB();
}
//property
public string Var1
{
get{ return var1; }
}
}
namespace N1
{
internal class ClassB
{
private void method()
{
// I need to access the value of Var1( property) from here, how to do this?
}
}
}
Pass an instance of ClassA into ClassB's constructor:
namespace N1
{
internal class ClassB
{
private ClassA _classAInstance;
public void ClassB(ClassA classAInstance)
{
_classAInstance = classAInstance;
}
private void method()
{
// You can access _classAInstance properties here
}
}
}
Update: I missed that a ClassB instance b was a private member on ClassA. Using my previous answer, you can just instantiate b in ClassA's constructor:
public ClassA()
{
var1 = "one";
b = new ClassB(this);
}
You need a reference to an instance of Class A.
So either change Class B constructor to accept a reference to class A
namespace N1
{
public class ClassA
{
string var1 = null;
private ClassB b;
public ClassA()
{
var1 = "one";
b = new ClassB(this);
}
//property
public string Var1
{
get { return var1; }
}
}
}
namespace N1
{
internal class ClassB
{
ClassA classA;
public ClassB(ClassA classARef)
{
classA = classARef;
}
private void method()
{
// I need to access the value of Var1( property) from here, how to do this?
string myString = classA.Var1;
}
}
}
or make ClassB's private method() take in a string? private void method(string classAVar1)
or make ClassA static (haha)
Well there are a couple of ways:
Change the access modifier of ClassB.Method to be public and make it take a string parameter.
Update the constructor of ClassB to take a string parameter and store it in a private field.
Add a public string property to ClassB.
Making a class internal just means the class is only available with files inside the same assembly.
You can't. Change access modifiers of either class A or B.
Purpose of internal class is to contain some internal logic implementation, and if you have need to access public classes' fields from it, probabli something wrong with app design

Making a superclass have a static variable that's different for each subclass in c#

Without any code in the subclasses, I'd like an abstract class to have a different copy of a static variable for each subclass. In C#
abstract class ClassA
{
static string theValue;
// just to demonstrate
public string GetValue()
{
return theValue;
}
...
}
class ClassB : ClassA { }
class ClassC : ClassA { }
and (for example):
(new ClassB()).GetValue(); // returns "Banana"
(new ClassC()).GetValue(); // returns "Coconut"
My current solution is this:
abstract class ClassA
{
static Dictionary<Type, string> theValue;
public string GetValue()
{
return theValue[this.GetType()];
}
...
}
While this works fine, I'm wondering if there's a more elegant or built-in way of doing this?
This is similar to Can I have different copies of a static variable for each different type of inheriting class, but I have no control over the subclasses
There is a more elegant way. You can exploit the fact that statics in a generic base class are different for each derived class of a different type
public abstract class BaseClass<T> where T : class
{
public static int x = 6;
public int MyProperty { get => x; set => x = value; }
}
For each child class, the static int x will be unique for each unique T
Lets derive two child classes, and we use the name of the child class as the generic T in the base class.
public class ChildA: BaseClass<ChildA>
{
}
public class ChildB : BaseClass<ChildB>
{
}
Now the static MyProperty is unique for both ChildA and ChildB
var TA = new ChildA();
TA.MyProperty = 8;
var TB = new ChildB();
TB.MyProperty = 4;
While this works fine, I'm wondering if there's a more elegant or built-in way of doing this?
There isn't really a built-in way of doing this, as you're kind of violating basic OO principles here. Your base class should have no knowledge of subclasses in traditional object oriented theory.
That being said, if you must do this, your implementation is probably about as good as you're going to get, unless you can add some other info to the subclasses directly. If you need to control this, and you can't change subclasses, this will probably be your best approach.
This is a little different than what you're asking for, but perhaps accomplishes the same thing.
class Program
{
static void Main(string[] args)
{
Console.WriteLine((new B()).theValue);
Console.WriteLine((new C()).theValue);
Console.ReadKey();
}
}
public abstract class A
{
public readonly string theValue;
protected A(string s)
{
theValue = s;
}
}
public class B : A
{
public B(): base("Banana")
{
}
}
public class C : A
{
public C(): base("Coconut")
{
}
}
There's an alternative solution which might or might not be better than yours, depending on the use case:
abstract class ClassA
{
private static class InternalClass<T> {
public static string Value;
}
public string GetValue()
{
return (string)typeof(InternalClass<>)
.MakeGenericType(GetType())
.GetField("Value", BindingFlags.Public | BindingFlags.Static)
.GetValue(null);
}
}
This approach is used in EqualityComparer<T>.Default. Of course, it's not used for this problem. You should really consider making GetValue abstract and override it in each derived class.
What about this?
class Base {
protected static SomeObjectType myVariable;
protected void doSomething()
{
Console.WriteLine( myVariable.SomeProperty );
}
}
class AAA : Base
{
static AAA()
{
myVariable = new SomeObjectType();
myVariable.SomeProperty = "A";
}
}
class BBB : Base
{
static BBB()
{
myVariable = new SomeObjectType();
myVariable.SomeProperty = "B";
}
}
It works for me.
Would be even nicer with Interface.
Simple solution: just use word "new".
public abstract class AbstractClass
{
public static int Variable;
}
public class RealizationA : AbstractClass
{
public new static int Variable;
}
public class RealizationB : AbstractClass
{
public new static int Variable;
}
And the result:
AbstractClass.Variable = 1;
RealizationA.Variable = 2;
RealizationB.Variable = 3;
Console.WriteLine(AbstractClass.Variable); //1
Console.WriteLine(RealizationA.Variable); //2
Console.WriteLine(RealizationB.Variable); //3
or you can use property:
//in abstract class
public static int Variable {get; set;}
//in child class
public static new int Variable {get; set;}
or function (but remember to add "new" to both variable and function):
//in abstract class
protected static int Variable;
public static int GetVariable() { return Variable; }
public static void SetVariable(int v) { Variable = v; }
//in child class
protected new static int Variable;
public static new int GetVariable() { return Variable; }
public static new void SetVariable(int v) { Variable = v; }
or you can use private variables (you don't need to use "new") with functions to get and set:
//in abstract class
private static int Variable;
//get and set methods
//in child class
private static int Variable;
//get and set methods

Categories