There is a lot going on here, so I will give an example of how I would handle this, and then I will try to explain it piece by piece.
public class Rule
{
private StringComparer _stringComparer;
public Rule(string name, RuleType type, StringComparer stringComparer = null)
{
if (name == null)
throw new ArgumentNullException("name", "name is null.");
if (type == null)
throw new ArgumentNullException("type", "type is null.");
if (stringComparer == null)
_stringComparer = StringComparer.CurrentCulture;
else
_stringComparer = stringComparer;
Name = name;
Type = type;
}
public RuleType Type { get; private set; }
public string Name { get; private set; }
public override bool Equals(object obj)
{
var rhs = obj as Rule;
if (rhs == null)
return false;
var namesEqual = _stringComparer.Equals(Name, rhs.Name);
var typesEqual = Type.Equals(rhs.Type);
if (namesEqual && typesEqual)
return true;
else
return false;
}
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hash = 17;
hash = hash * 23 + Name.GetHashCode();
hash = hash * 23 + Type.GetHashCode();
return hash;
}
}
}
How should I include the Comparer inside Rule class? Override Equals?
I'm not sure why you feel like you need a comparer class, but yes, I would override Equals and not even have a Comparer class.
And can I provide an option so that the Name comparison can be Culture or Case Insensitive or not?
I would follow the example of other .Net objects and have your constructor take in a StringComparer
that changes the functionality of your Rule class to be culture or case insensitive
If you are curious about the GetHashCode syntax you can look up best practices on GetHashCode. There is a pretty good explanation here https://stackoverflow.com/a/2733842/4708150
Having null checks on your public constructors is also good practice, and this way you don't have to do null checks in the GetHashCode method where you don't want to call GetHashCode on a null object.
You may want to be using Equals
when comparing types unless you are OK with a simple reference comparison. If you have other requirements for equality make sure you override Equals and GetHashCode in your RuleType class.
I added in private setters, which I'm guessing was just a typo on your part because they are needed to set values inside of the constructor. EDIT when I wrote this, I was using an old C# compiler. If you are using C# 6.0 or newer, defining only a getter is a great syntax for read-only auto-properties which allows you to set the property in the constructor, but nowhere else.