Reputation: 596
I've playing around with a class that acts as a public interface for a private List<T>
attribute. I noticed that the List<>
class has an attribute Length
that tells you how many elements it contains.
This is an attribute you cannot alter, and on the intellisense appears with an image of a spanner next to it. It is not a method as it does not require ()
after coding the name.
I've seen attributes of this type before, but never used them in my own classes. Does anybody have any idea how I can replicate Length
in my custom class?
Thanks, Mark
Upvotes: 0
Views: 1025
Reputation: 1187
Say for example you have a class like this:
public class MyClass
{
private string _str;
public MyClass()
{
_str = "Sample String";
}
public int Length
{
get
{
return _str.Length;
}
}
}
This is what's happening:
_str
."Sample String"
.Length
of type int
, and only giving it a get
accessor. Like your example, this only allows the value to be read, and not set.get
we then tell it to return the value of _str
's length.Using code similar to this you can implement a Length
attribute for any custom class.
Upvotes: 1
Reputation: 1739
I must admit that your question is a bit vague. It sounds like you want know how to create a read only attribute / property. This can be achieved by creating a property wrapper for a private field member of your class as follow:
class MyCustomClass
{
private int _length;
public int Length
{
get { return _length; }
}
}
Upvotes: 1
Reputation:
List<T> myList = new List<T>();
Now you can create your own implementation on your custom class. Something like:
public int Length {get {return myList.Count; }}
Upvotes: 1
Reputation: 9610
This is actually not a method, but a property.
So you could have define in your class
private List<string> myList = new List<string>();
public int NumberOfElements
{
get { return this.myList.Count; }
}
A normal property would be defined such as
public bool ColumnNames { get; set; }
Upvotes: 1
Reputation: 76557
If you currently have a class that contains a List
, then you can take advantage of the Count
property already present on it by exposing a property that simply uses that :
public class YourExampleList<T>
{
// Example of your inner list
private List<T> _list { get; set; }
// Use the Count property to expose a public "Length" equivalent
public int Length { get { return _list.Count; } }
}
Upvotes: 1
Reputation: 5314
It's a property with no setter. If you're wrapping a List<T>
you can just use it's Count as your own:
public int Count {get {return _myPrivateList.Count; } }
If you're using C# 6, you can use this:
public int Count => _myPrivateList.Count;
Upvotes: 5