Hide setter of property in nested classes in C# [duplicate] - c#

I have the nub of the code like this:
public class OuterClass
{
public static InnerClass GetInnerClass()
{
return new InnerClass() { MyProperty = 1 };
}
public class InnerClass
{
public int MyProperty { get; set; }
}
}
what is the solution to property named MyProperty just be settable from the InnerClass and the OuterClass, and out of these scopes, MyProperty just be readonly

There is no protection level for that. internal is the tightest you can use, which is limited to files in the same assembly. If you cannot make it a constructor parameter as has been proposed, you could use an interface:
public class OuterClass
{
public static InnerClass GetInnerClass()
{
return new InnerClassImpl() { MyProperty = 1 };
}
public interface InnerClass
{
int MyProperty { get; }
}
private class InnerClassImpl : InnerClass
{
public int MyProperty { get; set; }
}
}

I'm afraid there is no access modifier which allows that. You can create IInnerClass interface and make the property readonly within interface declaration:
public class OuterClass
{
public static IInnerClass GetInnerClass()
{
return new InnerClass() { MyProperty = 1 };
}
public interface IInnerClass
{
int MyProperty { get; }
}
private class InnerClass : IInnerClass
{
public int MyProperty { get; set; }
}
}

Related

How to access a property in another class?

I am working with a WPF .Net Core 3 project.
In my UnbalancedViewModel I need to access an ID from another class (TestRunDto.cs).
UnbalancedViewModel
public class UnbalancedViewModel : ViewModelBase, IUnbalancedViewModel
{
private TestRunApi _testRunApi;
public UnbalancedViewModel(TestRunApi testRunApi, INotificationManager notifications)
{
_testRunApi = testRunApi;
}
private void StartTestRunJobExecuted(object obj)
{
_testRunApi.StartTestRun(1); ////I need the Id from TestRunDto (TestRunDto.Id)
}
}
TestRunApi
public async Task<TestRunLiveValueDto> GetTestRunLiveValue(int jobRunId)
{
await using var dbContext = new AldebaDbContext(_connectionString);
return await TestRunInteractor.GetTestRunLiveValue(jobRunId, dbContext);
}
public async Task StartTestRun(int testRunId)
{
await using var dbContext = new AldebaDbContext(_connectionString);
await TestRunInteractor.StartTestRun(dbContext, testRunId);
}
TestRunLiveValueDto
public class TestRunLiveValueDto
{
public TestRunDto TestRun { get; }
public bool ShowInstantaneousValue { get; set; }
public bool EnableStart { get; set; }
public bool EnableStop { get; set; }
public bool EnableMeasure { get; set; }
public int RecipeRpm { get; }
public string ActualRecipeName { get; }
public int DefaultSetOfPlaneId { get; }
public ICollection<BalancePlaneDto> ListBalancePlane { get; }
public ICollection<SetOfPlaneDto> ListSetOfPlane { get; }
public ICollection<SensorVibrationDto> SensorVibrations { get; set; }
public ICollection<EstimationDto> InstantaneousValues { get; set; }
public ICollection<EstimationDto> EstimationsValues { get; set; }
private TestRunLiveValueDto(TestRunDto testRun, bool enableStart, bool enableStop, int recipeRpm, ICollection<SensorVibrationDto> sensorVibrations)
{
EnableStart = enableStart;
EnableStop = enableStop;
TestRun = testRun;
RecipeRpm = recipeRpm;
SensorVibrations = sensorVibrations;
}
public static TestRunLiveValueDto Create(TestRunDto testRun, bool enableStart, bool enableStop, int recipeRpm, ICollection<SensorVibrationDto> sensorVibrations)
=> new TestRunLiveValueDto(testRun, enableStart, enableStop, recipeRpm, sensorVibrations);
}
TestRunDto
public class TestRunDto
{
public int Id { get; set; }
public int JobRunId { get; set; }
public string Name { get; set; }
public int TestRunNumber { get; set; }
public RunState State { get; set; }
public ICollection<BalancePlaneDto> BalancePlanes { get; set; } // Todo remove
private TestRunDto(int id, int jobRunId, RunState state, string name, int testRunNumber)
{
Id = id;
JobRunId = jobRunId;
Name = name;
TestRunNumber = testRunNumber;
State = state;
}
public static TestRunDto Create(int id, int jobRunId, RunState state, string name, int testRunNumber)
=> new TestRunDto(id, jobRunId, state, name, testRunNumber);
}
I have been trying to understand this, but I can not get a hold of the proper method to do this. Do I first declare a new TestRunDto class in my viewmodel or am I supposed to access it some other way?
You need to ensure class A has a reference to an instance of class B to access the properties, for example one way of doing this is to pass class A to B in a method where you can manipulate or access properties.
public class FooA
{
public string PropertyA { get; set; }
}
public class FooB
{
public string PropertyB { get; set; }
public void CanAccessFooA(FooA a)
{
a.PropertyA = "See, I can access this here";
}
}
Another is to pass class A to B in the constructor (known as dependency-injection)
public class FooB
{
FooA _a;
public FooB(FooA a)
{
// Pass instance of FooA to constructor
// (inject dependency) and store as a member variable
this._a = a;
}
public string PropertB { get; set; }
public void CanAccessFooA()
{
if (this._a != null)
this._a.PropertyA = "See, I can access this here";
}
}
Exactly how to structure your code is up to you, but the principle remains the same: Class B can only access Class A if it has a reference to an instance of it.
Look into 'Dependency Injection' as there are many techniques to achieve this.
Edit
One such technique might be abstracting the code to provide the ID to both, like so
public class IdProvider
{
public int Id { get; set; }
}
public class FooA
{
private int _id;
public FooA(IdProvider idProvider)
{
_id = idProvider.Id;
}
}
public class FooB
{
private int _id;
public FooB(IdProvider idProvider)
{
_id = idProvider.Id;
}
}
Now both classes have the same ID;
StartTestRun takes the tesRunId as it's parameter.
public async Task StartTestRun(int testRunId)
{
I think you need to call StartTestRunJobExecuted with this testRunId.
You will to change
private void StartTestRunJobExecuted(object obj)
to
private void StartTestRunJobExecuted(int testRunIdn)
{
_testRunApi.StartTestRun(testRunId); ////I need the Id from TestRunDto (TestRunDto.Id)
}
(This based on me guessing).

Implement interface with subclassed properties

Given the interface
public interface baseInterface {
IList<double> listProperty { get; set; }
}
Is there any way to implement the interface with a property as a subclass of the property type as per the following example?
public class newClass : baseInterface
{
public List<double> listProperty { get; set; }
}
There are two approaches you could look at.
(1) You would have to use an explicit implementation to make it work:
public interface BaseInterface
{
IList<double> ListProperty { get; set; }
}
public class NewClass : BaseInterface
{
public List<double> ListProperty { get; set; }
IList<double> BaseInterface.ListProperty
{
get => this.ListProperty;
set => this.ListProperty = value.ToList();
}
}
(2) Use generics to allow for a subclass to be used:
public interface BaseInterface<L, T> where L : IList<T>
{
L ListProperty { get; set; }
}
public class NewClass : BaseInterface<List<double>, double>
{
public List<double> ListProperty { get; set; }
}
Both of these allow you to have a public List<double> ListProperty { get; set; } in NewClass.
You need to make interface generic.
public interface baseInterface <T> where T : IEnumerable<double>
{
T Data { get; set; }
}
public class derivedInterface : baseInterface <List<double>>
{
private List<double> m_Data = new List<double>();
public List<double> Data { get { return m_Data; }
set { this.m_MyData = value; }}
}

How to access Property of generic member in generic class [duplicate]

This question already has answers here:
Accessing properties through Generic type parameter
(2 answers)
Closed 6 years ago.
I am newbie in C#. I am trying to create a Generic class. I have three classes and a Main/Generic class.
Three Classes
public class A
{
public string Name { get; set; }
public string Address { get; set; }
public A(string _name, string _address)
{
Name = _name;
Address = _address;
}
}
public class B
{
public string Name { get; set; }
public string Address { get; set; }
public B(string _name, string _address)
{
Name = _name;
Address = _address;
}
}
public class C
{
public string Name { get; set; }
public string Address { get; set; }
public C(string _name, string _address)
{
Name = _name;
Address = _address;
}
}
Generic Class
public class GenericClass<T>
{
public GenericClass(T obj)
{
DynamicObject = obj;
}
public T DynamicObject { get; set; }
}
I have successfully created a Generic class.
class Program
{
static void Main(string[] args)
{
A objA = new A("Mohit", "India");
GenericClass<A> objGenericClass = new GenericClass<A>(objA);
Console.ReadLine();
}
}
Now, if I need to use Class A/B/C property in the Generic class. How can I use it? I know that class reference type decide on the runtime. So, I can't use it in below way.But, Is there any other way?
public class GenericClass<T>
{
public GenericClass(T obj)
{
DynamicObject = obj;
}
public T DynamicObject { get; set; }
public void UseClassPro()
{
Console.WriteLine("Address " + DynamicObject.Address);//Compile time error here.
}
}
The Other Answers are right, but...
I just want to point out: while those other answers promote valid C# code, they make the generic aspect of you implementation superflous. You don't need generics anymore:
Given a base class or interface like
public interface IHasAddress
{
string Address { get; }
}
you don't need a Generic class anymore for what you are trying to achive (from what i can tell by the code you provided):
public class NotSoGenericClass
{
public GenericClass(IHasAddress obj)
{
DynamicObject = obj;
}
public IHasAddress DynamicObject { get; set; }
}
So as you can see, you can easily implement the desired behaviour w/o generics.
For you as a Beginner, i'd recommend the following basic rules when it comes to generics:
When you think you have to use generics, force yourself to consider abstraction via interfaces, abstract classes or base classes first. This often leads to simpler and cleaner solutions.
Same goes with Reflection. When you think you need Reflection, consider generics (Rule 1 is valid at that point to)
But Nothings wrong with Generics, its just more complex and often not needed. Compare the class above with the generic solution:
public class GenericClass<T> where T : IHasAddress // just for the sake of generics
{
public GenericClass(T obj)
{
DynamicObject = obj;
}
public T DynamicObject { get; set; }
}
Looks more complex and doesn't add any benefit, does it? Also note that you need a Interface/baseclass no matter what. Otherwise, you could also use Reflection (not recommended).
To actually answer your question
The precise answer to your question is:
You have to define that you generic parameter has to be assignable to IHasAddress using
public class GenericClass<T> where T : IHasAddress
^^^^^^^^^^^^^^^^^^^^^
This Part
This way, the compiler knows that T inherits or is of type IHasAddress or what ever you define. You can also pass multiple types at this place which adds mor flexibility when it comes to designing your interfaces.
Maybe, there are points to consider in your usecase which are not obvious from the information you provided in the question. In that case, feel free to add some details and i'll be happy to deep dive into those as well.
define interface:
public interface IABC
{
string Name { get; set; }
string Address { get; set; }
}
and in your generic class definition specify this interface:
public class GenericClass<T> where T: IABC
{
public GenericClass(T obj)
{
DynamicObject = obj;
}
public IABC DynamicObject { get; set; }
}
All your 3 classes implemet this interface:
public class A : IABC
public class B : IABC
public class C : IABC
After that you could call properties of IABC
A objA = new A("Mohit", "India");
GenericClass<A> objGenericClass = new GenericClass<A>(objA);
var adress = objGenericClass.DynamicObject.Address;
If you have properties in your generic arguments that share type and name, use a base class:
public class Base
{
public string Address { get; set; }
public A(string _address)
{
Address = _address;
}
}
public class A : Base
{
public string Name { get; set; }
public A(string _name, string _address) : base(_address)
{
Name = _name;
}
}
public class B : Base
{
public string Name { get; set; }
public B(string _name, string _address) : base(_address)
{
Name = _name;
}
}
public class C : Base
{
public string Name { get; set; }
public C(string _name, string _address) : base(_address)
{
Name = _name;
}
}
You can then use the base class as a constraint to your generic class:
public class GenericClass<T> where T : Base
{
public GenericClass(T obj)
{
DynamicObject = obj;
}
public T DynamicObject { get; set; }
public void UseClassPro()
{
Console.WriteLine("Address " + DynamicObject.Address);//Compiles now
}
}
If you can not use a base class, use an interface:
public interface IBase
{
string Address { get; set; }
}
public class A : IBase
{
public string Name { get; set; }
public string Address { get; set; }
public A(string _name, string _address)
{
Name = _name;
Address = _address;
}
}
public class B : IBase
{
public string Name { get; set; }
public string Address { get; set; }
public B(string _name, string _address)
{
Name = _name;
Address = _address;
}
}
public class C : IBase
{
public string Name { get; set; }
public string Address { get; set; }
public C(string _name, string _address)
{
Name = _name;
Address = _address;
}
}
public class GenericClass<T> where T : IBase
{
public GenericClass(T obj)
{
DynamicObject = obj;
}
public T DynamicObject { get; set; }
public void UseClassPro()
{
Console.WriteLine("Address " + DynamicObject.Address);//Compiles now
}
}
There is no 'clean' way of getting a property from a generic class without inheritance, either through an interface or a base class, as shown in the other answers.
If you don't want to use inheritance, you can use reflection, although this is far less efficient than using an inherited class.
// the generic class
public class GenericClass<T> where T: IABC
{
public GenericClass(T obj)
{
DynamicObject = obj;
}
public IABC DynamicObject { get; set; }
public T GetPropertyValue<T>(string propertyName)
{
var obj = GetType().GetProperty(propertyName).GetValue(this);
return (T)Convert.ChangeType(obj, typeof(T))
}
}
A objA = new A("Mohit", "India");
GenericClass<A> objGenericClass = new GenericClass<A>(objA);
var address = objGenericClass.GetPropertyValue<string>("address");
I stress that this is an alternative to inheritance that will not be very fast, but it might suit your needs.
Add an interface that implements the similar properties like the following :
public interface IInfo
{
public string Name { get; set; }
public string Address { get; set; }
}
public class GenericClass<T> where T : IInfo
{
public GenericClass(T obj)
{
DynamicObject = obj;
}
public T DynamicObject { get; set; }
public void UseClassPro()
{
Console.WriteLine("Address " + DynamicObject.Address);
}
}

How to build a class with "generic" type and instancing it to the derived one?

I have this situation
public class CustomClass
{
public string stringTest { get; set; }
public int numberTest { get; set; }
public (xy) foo { get; set; }
}
Which will be my main class, then:
public class Base
{
public string somePropery { get; set; }
}
public class Derived : Base
{
public string someOtherProperty { get; set;}
}
public class Derived2 : Base
{
public string someHappyProperty { get; set;}
}
I would like to do this:
CustomClass test = new CustomClass()
{
foo = new Derived()
}
test.foo.someOtherProperty = "Wow!";
or
CustomClass test = new CustomClass()
{
foo = new Derived2()
}
test.foo.someHappyProperty = "Wow!";
Obviously I can't set foo's type as Base and I would prefer to avoid the use of the dynamic type, what is the correct way to handle this?
Make CustomClass generic:
public class CustomClass<T>
where T : Base
{
public string stringTest { get; set; }
public int numberTest { get; set; }
public T foo { get; set; }
}
You can now write:
CustomClass<Derived> test = new CustomClass<Derived>()
{
foo = new Derived()
};
test.foo.someOtherProperty = "Wow!";
Obviously I can't set foo's type as Base
Why not?
If you know it's going to be a Derived, set its type to Derived. If you don't, set it to Base. If you later want to check to see if it is a Derived and set Derived-specific members on it, you can use the is keyword:
if (test.foo is Derived)
{
((Derived) test.foo).someOtherProperty = "Wow!";
}

Adding additional properties without having to overwrite base properties

I have a number of classes deriving from an abstract base class. The concrete classes are stored in a container by references to base class. The concrete classes have many properties which are used to bind to pages in a FixedDocument.
I want to add aditional properties to the concrete classes at runtime which will also bind to the FixedDocument pages. I looked into the decorator pattern but it seems i have to override all the concrete class properties in the decorator class for them to be visible. Is there a way of adding a wrapper that is derived from the concrete class that inherits the values of the base properties as follows:
class BaseClass
{
public string Name { get; set; }
}
class ConcreteClass : BaseClass
{
public int MyProperty { get; set; }
}
class ConcreteClassWrapper : ConcreteClass
{
public int AdditionalProperty { get; set; }
public ConcreteClassWrapper(ConcreteClass cc)
{
base = cc;
}
}
private static void RunTime()
{
List<BaseClass> list = new List<BaseClass>();
ConcreteClass cc = new ConcreteClass()
{
Name = "Original",
MyProperty = 5
};
list.Add(cc);
cc = new ConcreteClassWrapper(cc)
{
AdditionalProperty = 10
};
}
Obviously i cant just set 'base = cc'. Is there anyway to achieve this?
Can you modify ConcreteClass so that it has an additional constructor:
class ConcreteClass : BaseClass
{
public int MyProperty { get; set; }
public ConcreteClass(ConcreteClass copy)
{
this.MyProperty = copy.MyProperty;
}
}
class ConcreteClassWrapper : ConcreteClass
{
public int AdditionalProperty { get; set; }
public ConcreteClassWrapper(ConcreteClass cc)
base(cc)
{
}
}
You can imagine the wrapper class to be defined like this
class ConcreteClassWrapper : ConcreteClass
{
public string Name { get; set; } // Inherited from BaseClass
public int MyProperty { get; set; } // Inherited from ConcreteClass
public int AdditionalProperty { get; set; }
}
It contains all the members declared in the all the base classes, since it inherits them.
You can create a new instance like this (assuming that you have a default constructor)
var wrapper = new ConcreteClassWrapper {
Name = "xy",
MyProperty = 5,
AdditionalProperty = 7
};
However, if you want the wrapper to be a true wrapper, do not inherit from the base class
class ConcreteClassWrapper
{
private ConcreteClass _cc;
public ConcreteClassWrapper(ConcreteClass cc)
{
_cc = cc;
}
public string Name { get { return _cc.Name; } set { _cc.Name = value; } }
public string MyProperty{ get { return _cc.MyProperty; } set { _cc.MyProperty = value; } }
public int AdditionalProperty { get; set; }
}

Categories

Resources