access property value of one class from another internal class in C# - 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

Related

Changing constructor parameter value structure map configuration

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

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

c# Accessing Creation Class Variables From Instance

Just a basic programming question.
public class ClassA
{
int i = 10;
void Start()
{
ClassB b = new ClassB(this);
b.DoSomething();
}
}
public class ClassB
{
ClassA a;
public ClassB(ClassA a)
{
this.a = a;
}
void DoSomething()
{
Console.WriteLine(a.i);
}
}
I would really like to omit the a:
Console.WriteLine(a.i);
->
Console.WriteLine(i);
What is the most reasonable method of achieving this?
(Note: ClassB must not inherit from ClassA, as ClassA inherits from something ClassB cannot. And I suppose I should say I don't want to pass parameters to the functions, so DoSomething(i) is not applicable.)
You can create a property. Please note that a.i still needs to be public for both your example and mine.
public class ClassB
{
private ClassA a;
public ClassB(ClassA a)
{
this.a = a;
}
public int i { get { return a.i; } }
void DoSomething()
{
Console.WriteLine(i);
}
}

Constructing class which's property can only be set in constructor, but get anywhere?

I'm trying to create a class which takes value a as a parameters in it's constructor.
It has a private member variable which stores this value. The value should not be changed afterwards.
Here's what I have, it works but I don't think it's the best solution out there:
internal class Foo
{
private int a;
public int A
{
get
{
return this.a;
}
}
public Foo(int a)
{
this.a = a;
}
}
So this way you can not access a from outside of the class, and A-property only has a get method. However, you can still change a from inside the class, and using a property which only returns one variable and nothing else feels stupid.
Am I doing this right, or is there a way to improve my code/more proper way to do this?
Additionally declare your private field readonly and you're there!
public class Foo
{
public Foo(int bar)
{
this.bar = bar;
}
public int Bar
{
get
{
return bar;
}
}
private readonly int bar;
}
“In C# 6 and later, you can initialize auto-implemented properties similarly to fields”. Just like you can initialize a readonly field in a constructor, you can initialize a get-only auto-implemented property in a constructor. Thus, the following now compiles:
public class Class1
{
public int A { get; }
public Class1(int a)
{
A = a;
}
}
…and the following yields an error:
public class Class1
{
public int A { get; }
public Class1(int a)
{
A = a;
}
public void Mutate()
{
// Class1.cs(11,9,11,10): error CS0200: Property or indexer 'Class1.A' cannot be assigned to -- it is read only
A++;
}
}
I like it—you get the terseness of field initialization with the interface/OOP-friendliness of properties.
internal class Foo
{
private readonly int _a;
public int A
{
get
{
return _a;
}
}
public Foo(int a)
{
_a = a;
}
}
This should do it.

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