Click here to Skip to main content
15,898,858 members

Comments by AtaChris (Top 4 by date)

AtaChris 2 days ago View    
Assume MyClass looks like as follows:

public MyClass
{
public MyClass()
{
// Parameterless constructor. Can be used by the class to initialize
// any value data required by an instance of this class but has no
// dependency on any outside data.
}

public MyClass(AnotherClass instance)
{
// Should take the instance of another class to use its memberfunctions and properties

}

...
}

And I would like to instantiate it as follows:

AnotherClass
{
MyClass _myClass {get; set} = new(this);
}

In such a case the compiler would say:

The this keyword was found outside of a property, method, or constructor or
A field initializer cannot reference the non-static field, method, or property 'name'.
AtaChris 8-Apr-24 12:21pm View    
Richards solution is what i was looking for.
Thank to you Richard an everybody else for the help !!!
AtaChris 8-Apr-24 3:30am View    
Thank you for this approach which would definitifely solve the Problem.
Maybe you can have a look to my comment @ Solution 2.
I would like to avoid to do value comparisons etc. in my Master class.
I need this feature for logging purposes.
My goal is to have a looger that shows namespace + class + property + old and new value of property when events in classes are fired.
The logger invocation should be located in the event handler of my Master class.
And I would like to hand over the info I got from sub classes directly to the logger.
AtaChris 8-Apr-24 3:14am View    
Thank you, this seems to be a solution that answers the question.
The only problem I see is the following:
My class Person and other classes not listed here carry many properties of different types.

This means I would have provide for every class a seperate event handler in Master class and I would have to ckeck each property of the classes in these event handlers. Another problem is, that I would have to compare old and new value in these event handlers to find out if they have changed.

I am looking for a solution where PropertyChangedEventHandler? sends the class and property name as well as its old and new value to a more generic PropertyChangedHandler in Master Class which is responsible for all Sub classes, so that I can retrieve the information I want from sender and/or e wihtout any forther validations in Master classes PropertyChangedHandler ?

In other words: is there a way to "inject" oldvalue and new value into
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));

So that all info I need is already prepared and send by Person class.