Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
Let's say I have a class that looks like this:
private class CompanyPerson
{
public Person Person { get; set; }
public string UserTokenGuid { get; set; }
}
And then Person looks like this:
private class Person
{
public Info Info { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
....
}
And Info...
private class Info
{
...
}
Now, if I create an instance of CompanyPerson:
CompanyPerson companyPerson = new CompanyPerson();
That's all good. But then if I immediadlty try this:
companyPerson.Person.FirstName = "Bob";
It throws an error because companyPerson.Person does not exist. I get that, and I understand why. But, this is a deep class with sub-classes that go 8 or 9 deep. Is there some way to instantiate all of the sub classes along with the parent class?
No, there is no generic way to instantiate "all child objects".
You may reflect over all properties to find them (including recursive walk), but actually creating objects is not generally possible.
Why:
some types may not have accessible constructors or no default constructor. Thus even if you know exact type of the property you could not instantiate it even via reflection
some properties can be of interface type. There is no way to magically know what actual type should be used.
there could be multiple types deriving from type of the property - again, no way to know what type should be used.
some properties can be read-only and could not be set outside of the class (like IList<int> Foo {get; private set;})
some properties actually should refer to same object which could not be described in any declarative way (MyType SecondInArray {get;set;})
In some cases you can use dependency injection container to instantiate types you interested in (after using reflection to find all properties). But really there is nothing better than actually setting all properties in constructors.
You should be able to instantiate new instances of each nested member as they appear like so...
var companyPerson = new CompanyPerson
{
Person = new Person
{
Info = new Info
{
// Keep instantiating nested properties as they appear
},
FirstName = "Bob",
LastName = "Doe"
},
UserTokenGuid = "someValue"
};
It can get a little hairy but that's the best way I can think to do it in one run instead of instantiating one nested object at a time.
My experience with this is from building deeply nested DTO models that translate to JSON objects for Web Services.
What you're asking is common during unit testing.
I don't know whether this is ever done in production, anyway you can create a stub (i.e. initialize a dummy instance of your class, properties included) using any testing framework; my favorite is NSubtitute, you just have to do this:
var APerson = Substitute.For<CompanyPerson>();
and you should be good to go.
Install it via NuGet:
Install-Package NSubstitute -Version 3.1.0
Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
Consider a simple class
public class MyClass
{
private int myProperty
...
public int MyProperty
{
get
{
return myProperty;
}
set
{
// some evaluation/condition
myProperty= value;
}
}
...
}
Now, if I want to create an empty constructor where I set default values for the class properties I could do this either this way:
public MyClass()
{
myProperty = 1;
...
}
or this way:
public MyClass()
{
MyProperty = 1;
...
}
Both examples seem valid, since I would never set a default value, that doesn't meet the requirements in the setter evaluation.
The question is, is there a best practice or doesn't it matter anyway?
What would be the advantage of one or the other be (as I can't find any)? Is there some reference, where this question is adressed?
So far I have come across code from many different developers that use either or both ways...
You can use both. But i prefer the first one. Why? Because the value that the property uses is directly assigned. For C# 6 above, you can use default value in a property directly without using constructor.
public class Person
{
public string FirstName { get; set; } = "<first_name>";
public string LastName { get; set; } = "<last_name">;
}
I personally like to set it as you done in first block.
For me it serve as additional fact of method is constructing object, not using alredy constructed. Also it makes me sure that properties is not called (they transform to set/get functions which results in couple of excess instruction).
But i believe that both variants are valid and maybe compiler optimizes properties to direct assignment.
For simple data first method is ok. But on more complex data, you could have a condition in the set (depending to another variable for example, set { if (Config.TestEnv) ...} so if you directly set the private value, you could be in trouble.
I'm using Redis Cache using Stack Exchange library.
I used cloudStructure library to use Redis Dictionary and Redis List.
Problem is when I try to retrieve values and if that model has a null
value for one list property it is throwing me below exception -
Jil.DeserializationException : Error occurred building a deserializer
for TestMainClass: Expected a
parameterless constructor for
System.Collections.Generic.ICollection1[TestChildClass]
---- Jil.Common.ConstructionException : Expected a parameterless constructor for
System.Collections.Generic.ICollection1[TestChildClass]
public class TestMainClass
{
public TestMainClass();
public int Id { get; set; }
public virtual ICollection<TestChildClass> Mydata { get; set; }
public string Title { get; set; }
}
public class TestChildClass
{
public TestChildClass();
public int Id { get; set; }
public string Value { get; set; }
}
Redis code for retrieve value:
RedisDictionary<int, TestMainClass> dictionary =
new RedisDictionary<int, TestMainClass>("localhost", "mylocaldictionary");
var result = await dictionary.Get(121);
What If I could not able to convert ICollection < T > into List < T >?
It might be a nice feature if the serialization library detected interfaces like ICollection<T> and IList<T> and implemented them with the concrete List<T> during deserialization, but ultimately: every feature needs to be thought of, considered (impact), designed, implemented, tested, documented and supported. It may be that the library author feels this is a great idea and should be implemented; it might not be high on the author's list, but they'd be more than happy to take a pull request; or there might be good reasons not to implement it.
In the interim, as a general rule that will solve virtually every serialization problem you will ever encounter with any library:
the moment the library doesn't work perfectly with your domain model: stop serializing your domain model - use a DTO instead
By which, I mean: create a separate class or classes that are designed with the specific choice of serializer in mind. If it wants List<T>: then use List<T>. If it wants public fields: use public fields. If it wants the types to be marked [Serializable]: mark the types [Serializable]. If it wants all type names to start with SuperMagic: then start the type name with SuperMagic. As soon as you divorce the domain model from the serialization model, all the problems go away. In addition: you can support multiple serializers in parallel, without getting into the scenario that A needs X and doesn't work with Y; B needs Y and doesn't work with X.
All you then need to do is write a few lines of code to map between the two similar models (or use libraries that do exactly that, like AutoMapper).
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have a program I'm writing that has a form with around 15 inputs that describe a type of machine that we make (model, length, width, height, motor type, color, etc). There are 12 different models of this machine so I have a sub class "machine" and then 12 separate classes that inherit the "machine class". In my form, one of the inputs the user selects is the model. I'm trying to figure out a way to pass the 15 items to the specific "model" class fields without having to type it out 12 times with a case/switch (based on which model is selected). Is there a way to pass the inputs to the parent class and then when you figure out which specific class you need to create, reference the data that was stored in the parent class? I hope that makes sense what I'm saying. I'm struggling with describing the situation. If I can provide any more info please let me know!!
Thanks!
I would suggest you to write an interface, let's say something like IMachineModel with the required methods/properties. Write as many classes as models you have and implement the previously created interface.
Provide in each concrete class the logic required. Then you only need to instantiate the suitable class and use its properties and methods implemented from the interface.
Quick Example:
public class FirstConcreteMachineModel : IMachineModel
{
public string Model { get; set; }
public void DoSomething()
{
Console.WriteLine("I am a machine of type 1");
}
}
public class SecondConcreteMachineModel : IMachineModel
{
public string Model { get; set; }
public void DoSomething()
{
Console.WriteLine("I am a machine of type 2");
}
}
public class MachineModelFactory
{
public static IMachineModel CreateMachineModel(string type)
{
//switch with all possible types
switch (type)
{
case "one":
return new FirstConcreteMachineModel { Model = type };
case "two":
return new SecondConcreteMachineModel { Model = type };
default:
throw new ArgumentException("Machine type not supported");
}
}
}
Then you can use it like:
IMachineModel machine = MachineModelFactory.CreateMachineModel("two");
machine.DoSomething();
It would print
I am a machine of type 2.
To add to Areks's answer -- you could create a factory that given the inputs returns a class that implements IMachineModel .... Internally you have a number of options of how to determine the concrete class including your switch statement or chain of responsibility
I have an object that takes plenty of parameters to its constructor (from 9 to 13 depending on use).
I want to avoid the ugliness of new MyObject(param1, param2, param3 ... param13).
My first attempt was to create a class MyObjectParams with properties with public getters and setters, it gives something like that :
var objectParams = new MyObjectParams
{
Param1 = ...,
Param2 = ...,
...
};
I see some big projects like SlimDX for their PresentParameters use this design. It looks better. But the class is not immutable.
I'd like my MyObjectParams to be immutable while still using a clean construction style. This is how it would look like with an immutable class :
var objectParams = new MyObjectParams
(
param1,
param2,
...
);
Note: it's just the long constructor line broken into several, so it's cleaner but still not as readable as initializers.
I was thinking of using named parameters to get both an immutable class and a more or less clean code, but I'm not sure whether this actually is a good idea:
var objectParams = new MyObjectParams
(
param1: ...,
param2: ...,
...
);
Should I use named parameters? Can you think of a better approach to solve this problem?
Edited regarding an answer below: unfortunately, I don't really think the design is bad. The 9 parameters really are required and remain constant throughout the entire life of the object. I cannot provide a default value for them as it is completely usage-dependant.
Have you looked into designing a solution in which you wouldn't need this amount of parameters? Having a lot of parameters makes the code very tightly coupled which reduces maintainability. Maybe you can redesign a small amount of code to a design which better separates the responsibilities of the class?
I really like the way The Zen of Python says a few things:
Simple is better than complex.
Complex is better than complicated.
[...]
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
I believe that having a dedicated Options class of some kind with the exhaustive list of all possible parameters is a good idea. Allow your MyObject constructor to require an Options instance, and then store a reference to the instance as a field on MyObject and refer to its getters/setters. (Storing the reference will be much superior to trying to parse the options and transfer their values to the MyObject instance. Now that would be messy.) With all data access delegated to the Options class, you will have successfully encapsulated the object's configuration, and you've designed a simple API for option access as the same time.
If Options has no reason to be publicly accessible, make it a private class definition and then you're free to maintain changes to Options logic without modifying MyObject. I believe that is a fair solution to you as the developer, and doesn't commit atrocities.
The constructor could have only a small number of parameters, the ones required for proper object initialization. You could then have a number of properties that can be set after the object has been constructed. You can set default values for those properties in the constructor and the client can set the ones he/she requires.
class Person
{
public Person(string name, int age)
{
Name = name;
Age = age;
Address = "Unknown";
Email = "Unknown";
}
public string Name {get; private set;}
public int Age {get; private set;}
public string Email {get; set;}
public string Address {get; set;}
}
Person p = new Person("John Doe", 30);
p.Email = "john.doe#example.org";
You could use the builder pattern to construct an immutable object.
public sealed class ComplexObject
{
public int PropA { get; private set; }
public string PropB { get; private set; }
public sealed class Builder
{
int _propA;
string _propB;
public Builder SetPropA(int propA)
{
// validate
_propA = propA;
return this;
}
public Builder SetPropB(string propB)
{
// validate
_propB = propB;
return this;
}
public CustomObject ToCustomObject()
{
return new CustomObject
{
PropA = _propA,
PropB = _propB
};
}
}
}
Usage
var custom =
new CustomObject.Builder()
.SetPropA(1)
.SetPropB("Test")
.ToCustomObject();
Final Thoughts
Despite my previous suggestion I am in no way against using named parameters if they are available.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 months ago.
Improve this question
I'm not talking about generic classes that declare properties or fields with the type of a generic parameter. I'm talking about generic properties which could be applied to both generic and non-generic classes.
I'm not talking about this:
public class Base<T>
{
public T BaseProperty { get; set; }
}
I'm talking about this:
public class Base
{
public T BaseProperty<T>
{
get
{
// Insert magic
}
set
{
// Insert magic
}
}
}
Or this:
public class Base<U>
{
public T BaseProperty<T>
{
get
{
// Insert magic
}
set
{
// Insert magic
}
}
public U OtherBaseProperty { get; set; }
}
The usage would go something like this:
var b = new Base();
b.BaseProperty<int> = 42;
int i = b.BaseProperty<int>;
b.BaseProperty<string> = "Hi";
string s = b.BaseProperty<string>;
Or for the second example:
var b = new Base<string>();
b.BaseProperty<int> = 42;
int i = b.BaseProperty<int>;
b.OtherBaseProperty = "Hi";
string s = b.OtherBaseProperty;
The // Insert Magic refers to handling each call to the generic property getter or setter that has a different type for the type parameter.
For example this:
b.BaseProperty<int> = 42;
Needs to be handled differently to:
b.BaseProperty<string> = "Hi";
I would envisage that for each type T if the getter is called before the setter is called then default(T) is returned.
When the setter is called the value is stored per type T so that when the getter is subsequently called the previous value that was set for that type is returned.
Note that under the covers properties are just methods.
Do you think this would be useful?
I've had a couple of times where I would have liked the ability to do this, yes.
However, the syntax involved would be pretty ugly, and it's sufficiently rarely useful that I think I prefer to just suck it up and go with generic methods.
No .
Without a killer use case, no. You can already achieve the same thing with a pair of generic methods, should you need it.
No.
Generic methods make sense, because they embody some (generic) operation that can sensibly be applied to different types.
But properties only make sense as uniquely named values with definite content. 'Generic properties', like you suggest, really only amounts to like-named properties with different signature and different content.
Here's one example where it would have been handy for me, if it would have been possible.
var settings = new Settings();
int timeout = settings<int>["CacheInMinutes"];
Where Settings loads an XML file of configuration variables.
That, compared to:
var settings = new Settings();
int timeout = int.Parse(settings["CacheInMinutes"]);
Really not much of a difference, but hey, I still would have preferred the generic indexer.
well, I have the situation that need generic property in non-generic class.
Example you have IComponent class that want to provide its parent IContainer with property Parent, since the component can belong to any container type. so you need to provide generic property rather than generic method
Component c = new Component();
Container p = new Container();
p.Add(c);
and then you access its parent using generic property (not aplicable now)
c.Parent.ContainerProperty;
c.Parent.ContainerMethod();
rather using verbose method like
c.Parent().ContainerProperty;
c.Parent().ContainerMethod();
Well, in this case generic property is more beautiful and make sense, since you don't need to input any argument.
If for some bizarre reason you decided you wanted it, you could sort of fake it with methods:
public class Thing
{
Dictionary<Type, object> xDict = new Dictionary<Type,object>();
public void set_X<T>(T x)
{
xDict[typeof(T)] = x;
}
public T get_X<T>()
{
return (T)xDict[typeof(T)];
}
}
Why you would want to is an entirely different matter, though. It generally makes more sense to start with something you want to do than some way you want to do it.