How does c# KeyedCollection initialize? [closed] - c#

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 7 years ago.
Improve this question
I'm reading some c# source codes.And something confuses me.In the following code,OptionSet is inherited from class KeyedCollection,and when OptionSet initialize like the following,it will at first call OptionSet() to get a new but empty OptionSet,then call Add() twice to insert { "h|?|help", v => Syntax() } and { "analyzer=", v => analyzer = v }.
I want to know why it initializes like this,why use Add()?
var p = new OptionSet()
{
{ "h|?|help", v => Syntax() },
{ "analyzer=", v => analyzer = v },
}
public class OptionSet : KeyedCollection<string, Option>{
public OptionSet ()
{
}
public OptionSet Add (string prototype, Action<string> action){...}
...
}

When you do this:
var p = new AnyCollection()
{
...
}
you are using Collection initializers.
From here:
Collection initializers let you specify one or more element
initializers when you initialize a collection class that implements
IEnumerable or a class with an Add extension method. The element
initializers can be a simple value, an expression or an object
initializer. By using a collection initializer you do not have to
specify multiple calls to the Add method of the class in your source
code; the compiler adds the calls.

Related

Why does Equals method of attributes compare fields? [closed]

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 1 year ago.
Improve this question
When I checked the attributes for equality, I noticed that they already have Equals method that compares the fields. For custom classes this comparison does not occur, since it is bad for performance, but why was an exception made for attributes?
Here's the code to make sure:
public class MyAttribute : Attribute
{
public int Value { get; }
public MyAttribute(int value) => Value = value;
}
public class MyClass
{
public int Value { get; }
public MyClass(int value) => Value = value;
}
public class Test
{
[Test]
public void TestEquals()
{
var myAttributeLeft = new MyAttribute(1);
var myAttributeRight = new MyAttribute(1);
var attributeEqualityResult = myAttributeLeft.Equals(myAttributeRight);
Console.WriteLine(attributeEqualityResult); // true
var myClassLeft = new MyClass(1);
var myClassRight = new MyClass(1);
var classEqualityResult = myClassLeft.Equals(myClassRight);
Console.WriteLine(classEqualityResult); // false
}
}
Custom attributes are not intended for use as domain objects: they are explicitly intended to represent metadata that are hard-coded at compile time. Assuming they are used as intended, this gives them a few special properties:
There are limits on the types that they are allowed to use: typically native types like int and string, and arrays of those native types.
The number of items that could be put into an array on the type is bounded by the number of items that are written into an actual code file.
In domain models it could create enormous performance penalties to compare the values of fields, properties, and elements of collections: you don't know how big the object structure for a given class might be, and a collection could have millions of items in it. But the restrictions mentioned above mean that the cost of an equality comparison for custom attributes is pretty well bounded. Evidently the creators of .NET felt that this made it worthwhile to give the base class value semantics, although the documentation includes remarks that recommend overriding the default implementation to use object equality or hard-coded value semantics instead.
Short answer: System.Attribute implements its own implementation of Equals which is different from the one in System.Object (from which MyClass class inherits)
You can find a more detailed answer on ms docs

Is there a way to add 2 different types to a new List in c#? [closed]

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 2 years ago.
Improve this question
I am trying to add 2 lists together but they are each of a different type, is there a way to do that?
My 2 lists
var customer = _context.GetInsuredData.FromSqlRaw("Execute dbo.GetDataID {0}", id).ToList();
var vehicle = _context.GetVehicleData.FromSqlRaw("Execute dbo.GetDataVehicle {0}", id).ToList();
My context:
public virtual DbQuery<Insured> GetInsuredData { get; set; }
public virtual DbQuery<Vehicle> GetVehicleData { get; set; }
Yes, it is possible.
Option 1 - Let the classes implement a common interface (or inherit a common base class):
public interface ICommonInterface
{ }
public class Insured : ICommonInterface
{ }
public class Vehicle : ICommonInterface
{ }
...then use a list with the generic type of the interface:
var list = new List<ICommonInterface>();
objectList.AddRange(insureds);
objectList.AddRange(vehicles);
Option 2 - Declare a list with the generic type object:
var list = new List<object>();
list.AddRange(insureds);
list.AddRange(vehicles);
You may need to rethink why you want to do this. Do the classes have something in common? Then use the interface/base class option. If not, what is the reason of adding objects of the different types to the same list? The problem you actually are trying to solve probably lies out of context of this question.

C# accessing a property of a generic class T [closed]

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 6 years ago.
Improve this question
I need to accessing a property of a generic Class T
I have this method in class generic
public T calcuste(T obj)
{
calcaulte testobj= new calcaulte ()
var t = GetValue(obj); // get the type of class for example that is calcaulte class
testobj.Id = obj.Id;// that is what I need to do accessing a property of T obj
}
Try following code.
public T calcuste(T obj)
{
calcaulte testobj= new calcaulte ();
calcaulte obj_calcaulte = obj as calcaulte;
if(obj_calcaulte != null)
{
testobj.Id = obj_calcaulte .Id;
}
}
You need to control for null since obj may be null or may belong to different class.

Adding local variable to List [closed]

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 9 years ago.
Improve this question
public class C
{
private List<myClass> _list = new List<myClass>();
public void MyFunction()
{
myClass myClassInstance = new myClass();
// working with myClassInstance
_list.Add(myClassInstance);
}
}
Problem is that List doesn't get populated, _list.Count is always 0 :(
Well, it is depends on your desing of myClass but I see two things;
class is a keyword, that's why you should use it as a #class
Keywords are predefined, reserved identifiers that have special
meanings to the compiler. They cannot be used as identifiers in your
program unless they include # as a prefix. For example, #if is a valid
identifier but if is not because if is a keyword.
your function method missed a return type which is void looks okey for your case.
You need to rename both the instance of myClass and function to something OTHER than C# keywords. At that point you can add the value to the list
public class C
{
private List<myClass> _list = new List<myClass>();
public void MyFunction()
{
myClass myClassInstance = new myClass();
// working with myClassInstance
_list.Add(myClassInstance);
}
}

How to pass difference type into a function like passing variables [closed]

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
DatePickerOfItemsControl, TextBoxOfItemsControl, ComboBoxOfItemsControl are class, how to pass these class into a function like passing variables
for the function to save these class or type as a variable and use it to create instance when needed
ifactory.AddControl(DatePickerOfItemsControl);
ifactory.AddControl(TextBoxOfItemsControl);
//ifactory.AddControl(textbox2);
ifactory.AddControl(ComboBoxOfItemsControl);
ifactory.AddControl(RadioBoxOfItemsControl);
public void AddControl(Object c)
{
datepickerclass = DatePickerOfItemsControl;
public void Apply()
{
datepickerclass datepicker = new datepickerclass();
Use Type:
public void AddControl(Type c)
{
}
You can use Activator.CreateInstance() to then create an instance of the type:
public void AddControl(Type c)
{
object o = Activator.CreateInstance(c);
}
Then call it like this:
AddControl(typeof(RadioBoxOfItemsControl));
See MSDN -
http://msdn.microsoft.com/en-us/library/wccyzw83.aspx
I'm not really sure but I think your trying to generalise the creation of controls so how about something like this:
ifactory.AddControl(() => { new datepickerclass() });
public void AddControl<T>(Func<T> factory)
where T : BaseControlType
{
var instanceOfControl = factory();

Categories