I have a silly question here.
I define a class with many data members, like this:
public class A
{
public string Name { get; set; }
public double Score { get; set; }
//...many members
public C Direction { get; set; }
public List<B> NameValue1 { get; set; }
public List<string> NameValue2 { get; set; }
//...many members
}
Now, I'm writing unit test code and want to compare two instances of class A.
But I found this doesn't work:
Assert.AreEquals(a1, a2);
I must override Equals method to do that? C# can't help with this by default?
Or I can serialize these two guys and compare the filestream?
Thank you.
The default equality implementation, for reference types, is reference equality: "is this the same instance". For equivalence, yes, you should write that yourself if you need that, but: it is rarely all that useful really (and there's a problem, because if you override Equals you should override GetHashCode too, with a suitably parallel implementation.
Personally, I'd compare manually in your unit test if this code isn't part of your main system.
Lists are a pain too, since there are three options:
same list instance
different lists with same content instances
different lists with equivalent content instances
You probably mean the last, but that is the same problem, repeated.
Re serialization: that is tricky too, since it depends on the serializer and the contents. I wouldn't recommend that route unless a: your type is already being used for serialization, and b: your chosen serializer guarantees the semantic you mean. For example, BinaryFormatter does not (I can provide a concrete example if you want, but trust me: this is not guaranteed).
Related
I want to create a little testing tool for my program, which fills all properties of a random object (unknown type at compile time). A sample structure:
public class HeadObject
{
public Company Company { get; set; }
public CompanyAddress CompanyAddress { get; set; }
public List<Details> Details{ get; set; }
public ApplicationUser AppUser { get; set; }
}
and e.g the class Company would look like this:
public class Company
{
public string CompanyName{ get; set; }
public string PhoneNumber{ get; set; }
public Address Adress{ get; set; }
public int CompanyNo{ get; set; }
public List<Employee> Employees{ get; set; }
}
its pretty simplified because in each HeadOjbect there are around 30 properties which may contain sub properties or a property can be a list etc.. I need to populate ~30 HeadObjects at runtime. I already tried it with different libraries like GenFu, nBuilder or Bogus.
The last 2 have the problem that I have to fill the properties by myself only the data is generated. GenFu looks like it can only deal with primitive properties like int, string, ... And if you imagine the HeadObject as a root of a tree, then there would be
~ 300 Nodes per tree
Height of a tree: between 1 and 7(!)
~30 Different trees (HeadObjects)
so it would take days to write this all down by myself and maintenance would be a pain.
I appreciate any kind of idea.
UPDATE
Thanks for your replies! How can I initialize the objects? e.g I get the Company property of my head object and then I want to initialize it to be able to fill it. My method (its recursive) starts like this:
private static T FillAllProperties<T>(T masterObject) where T : new()
{
try
{
Type masterType = masterObject.GetType();
T headObject = new T();
......IF primitive Type fill it and return the value
otherwise get Properties into firstProperties.......
foreach (var propertyInfo in firstProperties)
{
var objectInstance = FillAllProperties(propertyInfo.PropertyType);
headObject.GetType().GetProperty($"{propertyInfo.Name}").SetValue(headObject, objectInstance, null);
}
Now I have 2 questions:
is my way to initialize the generic type correct?
at the recursive call I get the following error :" The type 'System.Type' must have a public parameterless constructor in order to use it as parameter 'T'....
I probably need another "construction" for this algorithm, but how..?
You are going to go through deep pain...
Basically the idea is to iterate through the object's properties and randomly fill them.
You can iterate using YourObject.GetType().GetProperties() then using PropertyInfo.PropertyType to know the type.
Then with each Proprety Type you can check whether it is a simple (i.e. int, double...) structure or a more complex object (by using Type.IsPrimitive, Type.IsClass or Type.IsValueType).
If it a class, you recursively call the same method, because it means you have a complex type.
If it is a structure, then maybe you should iterate over the fields instead of the properies ?
If it is a primitive you can set its value using PropertyInfo.SetValue(), but how are you going to randomize anything ? You need to perform a switch on .Net base types then generate a value at random for each type.
By the way, a string is a class, not a primitive, so you will need to make a special case for this one.
Also, List<string> is a funny one, because it is an Enumerable object. So it is another specific case.
And if you want to have fun, try out a Dictionary, or better, Tuple...
Anyway, there is no simple way to perform this. Your simple testing tool will soon become a nightmare because of all the cases you couldn't even see from far away...
Maybe there is a better option to test your program than filling it with random values that don't have any actual meaning ?
If you do not know the properties at runtime, you will have to use Reflection. But starting with 30 properties, I would probably use it regardless (or look if I made any mistakes in my design). Writing that much manually is just too prone to mistakes.
A alternative might be to have a ISelfRandomizing interface with a SelfRandomize() function, so each type input can carry it's own randomization code. And hope people actually provide it.
Something that might be viable for your case: structs by default use reflection for comparison. What would be the equivalent of a base class for them, has reflection based fallback code. You are invited to override it, but if you do not it just "works". You could make a abstract base class that you use for all those classes. That way you only need to write the reflection code once.
As for the actual randomization: Random. A common mistake is creating new instances of Random in a loop. Do not do that. You want to keep a single Random instance around as long as possible, for optimal randomisation. I have no sensible way to transform a Integer return into a string, so the next best non-sensible thing is to create a large random number and call ToString() on it. That will give you something to put in those spots at least.
I don't have access to the definition of a class but I can inherit from it. I want in the derived class to be denied from accessing some fields that are public in the base class for obvious reasons of accidentally accessing/setting/getting the fields/properties.
What choices do I have?
EDIT:
Why the downvote? I have to refactor a large code that was using the said inherited fields and I have to manually treat the lines involving not only those but also the chained inherited fields down the hierarchical tree.
Additionally I have to make sure even I or my partners won't access those fields/properties and still using those intentedly inherited.
EDIT:
A distinction must be made between 2 separate cases: when the programmer designs the application from ground up and when s/he is compelled to proceed from inaccessible code.
In the former case s/he is responsible for applying OOP and design patterns as best fit for the future intended use s/he envisions.
In the latter, situations often come up when the programmer needs to develop from a slightly modified proprietary given class to avoid unneeded complications for the long term. Often times the original code designer can't exhaust the use cases. Thus the developer makes a custom version of the class with the "promise" the original class won't be used and even if ever used, it will only be used for the purposes originally intended, and no inheritance or other relation exists with the new version. This new version would have additional members and other missing members as compared to the original class. This would be consistent with I in SOLID, albeit adapted for classes.
In these cases I admit that inheritance is not the way to go, as it has a different purpose and the developer would break L (and conceptually I) from SOLID by using inheritance. But there's no feature of any language that provides for this, so there's no choice left.
The way I see it, you need to use the Decorator/Wrapper design pattern. Instead of inherinting it, you wrap a class around it.
The class you have:
public class SealedPerson
{
public string Prop1 {get;set;}
public string Prop2 {get;set;}
}
The class you need:
public class SealedPersonWrapper
{
public SealedPersonWrapper(SealedPerson person)
{
this.Prop1 = person.Prop1;
}
public string Prop1 {get; private set;}
}
You can do this by separating interfaces:
public class BaseClass:IBase
{
private int A;
private int B;
void IBase.SetA()
{
A=10;
}
public void SetB()
{
B=10;
}
}
public class DerivedClass:BaseClass
{
public Set()
{
base.SetB();
//method SetA will not accessible through base class, but will accessible with IBase interface
}
}
Hide the inherited fields/properties/methods that you want unusable and make so using them would generate an error, like so:
public class Base // not owned code
{
public int free {get; set;};
public int limited {get; set;};
}
public class Derived:Base // owned code
{
// public new int limited; // NOT hidden! Still accessing Base.limited!
// working:
[Obsolete("Inaccessible hidden inherited variable", true)]
public new int limited {get; set;}
}
true is necessary to prohibit the compilation (trigger an error) instead of compiling with warning.
It's way much easier to write code especially for the unwanted fields than for the wanted ones, since using 90% of the base class.
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 8 years ago.
Improve this question
I can declare functions and properties in an interface, but I cannot implement them. When I inherit from the interface, I now have to implement all these members in my class. If I have to do that, what's the point of declaring the interface at all?
For example, here's an example interface:
namespace InterfaceExample
{
public interface IVehicle
{
int Doors { get; set; }
int Wheels { get; set; }
Color VehicleColor { get; set; }
int TopSpeed { get; set; }
int Cylinders { get; set; }
int CurrentSpeed { get; }
string DisplayTopSpeed();
void Accelerate(int step);
}
}
I've declared all the properties and functions in this interface. Now, when I use this interface in my class like this:
namespace InterfaceExample
{
public class Motorcycle : IVehicle
{
private int _currentSpeed = 0;
public int Doors { get; set; }
public int Wheels { get; set; }
public Color VehicleColor { get; set; }
public int TopSpeed { get; set; }
public int HorsePower { get; set; }
public int Cylinders { get; set; }
public int CurrentSpeed
{
get { return _currentSpeed; }
}
public Motorcycle(int doors, int wheels, Color color, int topSpeed, int horsePower, int cylinders, int currentSpeed)
{
this.Doors = doors;
this.Wheels = wheels;
this.VehicleColor = color;
this.TopSpeed = topSpeed;
this.HorsePower = horsePower;
this.Cylinders = cylinders;
this._currentSpeed = currentSpeed;
}
public string DisplayTopSpeed()
{
return "Top speed is: " + this.TopSpeed;
}
public void Accelerate(int step)
{
this._currentSpeed += step;
}
}
I have to declare all the properties again.
So why bother at all with the interface in the first place? It seems like a waste of time, since I will be implementing all the members in my class anyhow.
As other answers emphasize interfaces tell you what to do and how to do is up to you to implement.
1. Then why I waste my time in create a Interface If I have to declare all the properties and functions of My Interface in my class.
Ok. You are creating a Motorcycle and by implementing the interface IVehicle, the MotorCycle class is forced to implement all the members of the interface IVehicle.
If you had not used an interface called IVehicle, you might actually forget to implement something that you should have been implemented.
Tomorrow, if somebody wants to build a Car then you can implement from IVehicle, people can implement all its methods and customize.
The purpose of the IVehicle interface is to make sure that whenever you build a vehicle class, it reminds and forces you to make sure that you rightly build a vehicle
2. For Properties, interface is a waste of time ?
No and definitely not.
For example, whenever you want to return the vehicle speed, instead of just rounding of the vehicle speed to integer you want in exact floating point,
10 // public float currentSpeed { get; set; }
10.5 // public float currentSpeed { get {return {//write custom logic}; set; }
Notice the customisation in Get accessor of the property.
3. When should abstract class be used ?
Abstract class should be used when all derived class would be using some repeated method. For example,
public abstract Class AbstractClass
{
public virtual int Doors { get; set; }
public virtual int Wheels { get; set; }
public virtual Color VehicleColor { get; set; }
public virtual int TopSpeed { get; set; }
public virtual int HorsePower { get; set; }
public virtual int Cylinders { get; set; }
public string WhatSideDriving
{
if (Country == "US") return "Keep Right";
if (Country == "India") return "Keep Left";
}
}
Do note that the method WhatSideDriving is already implemented and can be used by all the classes that derive from this class. However other members can be overridden and can be implemented according to the required functionality.
Then why I waste my time in create a Interface If I have to declare all the properties and functions of My Interface in my class.
Because an interface is just that; a (public) interface. It does not define an implementation, only the methods and properties used to interface to any of its implementations.
Of course, implementors of said interface must define the implementation of it. How else would you expect this to work?
That said, it's not inconceivable that properties could be implicitly (and invisibly) implemented as automatic properties, but that doesn't work for methods, and you often need more than get; set; anyway, so it would provide little benefit (i.e., a feature that isn't worth the effort).
Strictly speaking, declaring an interface is a waste of time. You could skip the interface and save some time.
However, you would be cutting the wrong corner. While it's a bit of extra time and work, in the long run interfaces are invaluable. One of the marks of a truly great software engineer is being able to design interfaces well.
To be less abstract, the interface is designed for precisely that purpose: To formalize the interface between two kinds of classes (in other words, how the two classes work together). It is a bit like a contract between classes, where each class says what they promise to provide and what they will expect. Your IVehicle example, for instance, vows that it will always have a property called doors. Then, any code which works with IVehicle can trust all implementations of IVehicle to always have a Doors. You can now safely write code which accesses IVehicle.Doors knowing that no matter what particular implementation happens to get passed to this method, your code will definitely work - even if the Vehicles package developer decides to one day add some vehicles you've never heard about or considered!
When you have only one small class implementing the interface, and you are the only developer, interfaces may be superfluous. However, what if there were multiple kinds of vehicles, each with their own logic and different members, which must nevertheless be used by some general code? For example, a vehicle tracking manager must handle classes Car, Truck, Plane and so on. Why not? They all have a speed and position, and that's all that matters.
Moreover, when you let other developers write their own vehicles, the interface is a great way of showing them how they must do this for it to work with the rest of your code.
Likewise, when you work on a large project, and split each part between different developers, well-designed interfaces can ensure that these programmers, working on different parts of the project in relative isolation, will still create a whole which works thanks to parts that fit together nicely.
Similarly, a good interface is a great way to start a complicated class even when coding on your own: It will help you keep track of what you need to implement and how, but unlike a more familiar technical specification, an interface can be understood by the compiler so that it can assist you in many ways (such as help from IntelliSense when you want to write logic using parts of your class that you will implement later).
In C# particularly, interfaces also have a practical benefit. You can't inherit from more than one class or abstract class in C# (unlike C++). This is done because multiple inheritance turns out to make life very difficult for programmers sometimes. But you can inherit from multiple interfaces, and because they are only interfaces (with no implementation) the "multiple inheritance" thing is much less of an issue.
Lastly, a real world example: Microsoft has provided for you a List.Sort method which will helpfully sort a list of any object. It is obviously easy to do this for things like numbers and strings, but it is possible to make it sort arbitrary objects you made, like vehicles. But how could Microsoft possibly know what kinds of classes you will implement, and how you intend for these to be sorted? They don't, but they provide for you an interface called IComparable. This defines the methods that sorting code needs to call to be able to compare two objects for sorting. If the object you put into your list implements this IComparable, you will have told Microsoft's List.Sort code how your objects should be sorted, and now you no longer have to write your own sort function since you can just use the well designed, tested, documented and debugged Microsoft one.
As an exercise, try writing a program which takes a list of Triangle classes (which have only a, b, c fields that store the length of each side, and a CalculateArea method) and then sorts it by area using Microsoft's List.Sort. Don't write your own sorting code, and don't use thing like LINQ OrderBy, instead do it by making Triangle implement IComparable. Then think about this: If you were the project manager in charge of development of all the .NET libraries, how would you write a sort function that anyone can use, even with their own weird classes?
You create an interface if you need to create an interface.
You can pass all types of vehicles as the interface type to methods. If you declare all three of the following and you need to calculate their fuel efficiency, you would need three separate methods that do that.
example:
public class Truck {}
public class Car {}
public class Motorcycle {}
With an interface you need one method:
public int GetFuelEfficiency(IVehicle vehicle)
The interface requires you or anyone else implementing it to declare ALL of its properties and methods. This way all classes implementing the interface will contain all the necessary properties and methods to be treated by other code in the same manner regardless of the classes specific implementations.
There are yet other reasons for declaring an interface like the lack of multiple inheritance in C#, etc.
Interfaces are definitions, and not implementations. Classes are both implementations and definitions.
The point of an interface is to separate implementation from definition, so that that the consumer does not have any knowledge of the actual object used to implement the interface.
Yes, it's more work, but good design is always more work than bad.
Interface provides a blueprint for implementation. You have the freedom to create the actual class from that blueprint. To be able to do so, you have to define all the aspects of that blueprint.
Interface is mostly used to create pluggable interfaces to applications and are also used to support multiple inheritance.
References:
Code Project
DZone
MSDN - Interfaces - C# Programming Guide
MSDN - When to use Interfaces
You may also use Abstract classes if it suits your purpose. But Abstract class != Interface.
I've often seen and used enums with attached attributes to do some basic things such as providing a display name or description:
public enum Movement {
[DisplayName("Turned Right")]
TurnedRight,
[DisplayName("Turned Left")]
[Description("Execute 90 degree turn to the left")]
TurnedLeft,
// ...
}
And have had a set of extension methods to support the attributes:
public static string GetDisplayName(this Movement movement) { ... }
public static Movement GetNextTurn(this Movement movement, ...) { ... }
Following this pattern, additional existing or custom attributes could be applied to the fields to do other things. It is almost as if the enum can work as the simple enumerated value type it is and as a more rich immutable value object with a number of fields:
public class Movement
{
public int Value { get; set; } // i.e. the type backing the enum
public string DisplayName { get; set; }
public string Description { get; set; }
public Movement GetNextTurn(...) { ... }
// ...
}
In this way, it can "travel" as a simple field during serialization, be quickly compared, etc. yet behavior can be "internalized" (ala OOP).
That said, I recognize this may be considered an anti-pattern. At the same time part of me considers this useful enough that the anti might be too strict.
I would consider this to be a poor pattern in C# simply because the language support for declaring and accessing attributes is so crippled; they aren't meant to be stores of very much data. It's a pain to declare attributes with non-trivial values, and it's a pain to get the value of an attribute. As soon as you want something remotely interesting associated with your enum (like a method that computes something on the enum, or an attribute that contains a non-primitive data type) you either need to refactor it to a class or put the other thing in some out-of-band place.
It's not really any more difficult to make an immutable class with some static instances holding the same information, and in my opinion, it's more idiomatic.
I'd say it's an anti-pattern. Here's why. Let's take your existing enum (stripping attributes for brevity here):
public enum Movement
{
TurnedRight,
TurnedLeft,
Stopped,
Started
}
Now, let's say the need expands to be something a little more precise; say, a change in heading and/or velocity, turning one "field" in your "pseudo-class" into two:
public sealed class Movement
{
double HeadingDelta { get; private set; }
double VelocityDelta { get; private set; }
// other methods here
}
So, you have a codified enum that now has to be transformed into an immutable class because you're now tracking two orthogonal (but still immutable) properties that really do belong together in the same interface. Any code that you'd written against your "rich enum" now has to be gutted and reworked significantly; whereas, if you'd started with it as a class, you'd likely have less work to do.
You have to ask how the code is going to be maintained over time, and if the rich enum is going to be more maintainable than the class. My bet is that it wouldn't be more maintainable. Also, as mquander pointed out, the class-based approach is more idiomatic in C#.
Something else to consider, as well. If the object is immutable and is a struct rather than a class, you get the same pass-by-value semantics and negligible differences in the serialization size and the runtime size of the object as you would with the enum.
How can I get a Types FieldInfos/PropertyInfos as a MemberInfo array in the order they are laid out in the class?
class Test
{
public bool First { get; set; }
public int Second;
public string Third { get; set; }
}
http://msdn.microsoft.com/en-us/library/ch9714z3.aspx
The GetFields method does not return fields in a particular order, such as alphabetical or declaration order. Your code must not depend on the order in which fields are returned, because that order varies.
http://msdn.microsoft.com/en-us/library/kyaxdd3x.aspx
The GetProperties method does not return properties in a particular order, such as alphabetical or declaration order. Your code must not depend on the order in which properties are returned, because that order varies.
You would need to define order yourself, perhaps with attributes:
class Test
{
[Order(1)] public bool First { get; set; }
[Order(2)] public int Second;
[Order(3)] public string Third { get; set; }
}
...
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field,
Inherited = true, AllowMultiple = false)]
[ImmutableObject(true)]
public sealed class OrderAttribute : Attribute {
private readonly int order;
public int Order { get { return order; } }
public OrderAttribute(int order) {this.order = order;}
}
Look at Mono.Cecil
If the Serializer is able to do source ordering it won't be because of the PDB debug info.
I assume reflection loses the ordering because it will (potentially) return a mix of direct and inherited members. There is no 'correct' ordering of that mix.
Mono.Cecil will let you get directly at the structures in the managed assembly, as well as at the CIL code. Mono.cecil rocks big time and will not eat your puppies. It is the fastestest method to analyze your assemblies, and you don't even have to have them loaded.
Mono.Cecil goes on to write a new assembly if you wish, but this propaganda is getting way off-topic.
Go get Mono.Cecil
You can't, as this info is not relevant to the execution or functionality of the class. Why would you want to retrieve this info anyway?
The line number information is not compiled in to the assembly, it is stored in the .PDB file for the use of debugger.
Although technically it may be possible to get the information you are looking from the PDB file, I don't think that will be a good idea either, as the PDB file will not be present in the production environment. Even if it is there there is no guarantee that it is in sync with the DLL.
I have found more information when trying to google the other way around. Like JbEvain pointed out, it is confirmed that there is no way to control the order in which the compiler outputs members in CIL classes. This even pertains to XmlSerializer
A number of interesting posts have posted here:
On that topic, I found that in fact to have reliable ordering (In .NET 2.0, you can also “explicitly“ control this using the XmlElementAttribute.Order)[pluralsight-training.net/community/blogs/tewald/archive/2006/04/… and others
http://www.pluralsight-training.net/community/blogs/craig/archive/2006/04/06/21176.aspx
http://www.pluralsight-training.net/community/blogs/craig/archive/2006/04/18/21933.aspx
http://www.pluralsight-training.net/community/blogs/tewald/archive/2006/04/18/21964.aspx
This should give a good background to this discussion. It now really depends on what the original poster needed this information for whether there can even be a solution, and if so, to find a route to achieving that goal.