Reputation: 1
Hi I want create class Set
which inherited from List<int>
class Set : List<int>
{
public void Add(tmp)
public void Pop(tmp)
public print()
}
But I have problem how should look consturctor could someone give me example? I know how should looks methods(I will write them myself).
Upvotes: 0
Views: 43
Reputation: 396
Within the class type ctor
then hit tab twice, this will create the default constructor:
public Set()
{
}
Using Set as a class name could be confusing though as the 'set' keyword is used in properties
Upvotes: 0
Reputation: 456
An alternative possibility is the use of extension methods as it seems to me you are only trying to add functionality to List by way of methods. Here is an example:
public static class ListExtensions
{
/// <summary>
/// Adds an empty Dropdown Option at the start of the list
/// If the list is null then null will be returned and nothing happens
/// </summary>
/// <param name="list">
/// List of dropdown options
/// </param>
/// <returns >The list of dropdown options with the prepended empty option</returns>
public static IList<SelectListItem> AddEmpty(this IList<SelectListItem> list)
{
list?.Insert(0, new SelectListItem {Value = string.Empty, Text = Resources.Labels.ChooseListItem});
return list;
}
}
Upvotes: 0
Reputation: 26446
List<T>
has a parameterless constructor, so you don't need to do anything within your constructor.
You can even omit it altogether if you don't plan on adding constructors with parameters, it'll automatically run the empty constructor on the base class when you create a new Set()
:
class Set : List<int>
{
public new void Add(int tmp)
{
// custom logic here
base.Add(tmp);
}
}
Set myset = new Set();
myset.Add(43);
Note that you chose to inherit from List<int>
, which means that all members defined by List<int>
are also available on your Set
class. An alternative solution is to wrap the list:
class Set : IEnumerable<int>
{
private readonly List<int> wrappedCollection = new List<int>();
public void Add(int value)
{
wrappedCollection.Add(value);
}
...
}
This way you can choose which interfaces you want to implement, and add additional functionality like your print()
method.
Upvotes: 1