Providing Access to a Class Private Member Attributes [duplicate] - c#

This question already has answers here:
Properties vs Methods
(16 answers)
Closed 4 years ago.
I was wondering what is more efficient or the best practice for returning attributes of private members. For example:
class Foo
{
private List<int> fooList;
public Foo()
{
Random random = new Random();
fooList = new List<int>(random.Next(1, 100));
}
//
public int Count { get { return fooList.Count; } }
// or
public int Count() { return fooList.Count; }
}
Which is best if I do not want to give public access to my list?

Based on your example, you should stay with a property. Because the fooList.Count is a property.

Related

Readonly Field used as a normal field [duplicate]

This question already has answers here:
Are C# readonly field's allowed to be modify outside of the class?
(3 answers)
Prevent other classes from altering a list in a class
(4 answers)
Closed 1 year ago.
I was checking an online tutorial video and I noticed this code modifying a readonly field without constructor and it was working fine. How & Why it works?
public class Journal
{
private readonly List<string> entries = new List<string>();
private static int count = 0;
public int AddEntry(string text)
{
entries.Add($"{++count}: {text}");
return count; // memento pattern!
}
public void RemoveEntry(int index)
{
entries.RemoveAt(index);
}
public override string ToString()
{
return string.Join(Environment.NewLine, entries);
}
}
public class Demo
{
static void Main(string[] args)
{
var j = new Journal();
j.AddEntry("I cried today.");
j.AddEntry("I ate a mango.");
WriteLine(j);
}
}
output:
I cried today.
I ate a mango.
What is really happening here is that a method called on the entries readonly field and it Does NOT change the reference of the entries field.
Changing the reference of the readonly field is a compile error, but calling a method on the readonly (whatever it does internally) has no problem at all
Try the following statement
entries = new List<string>();
and you will see the error

How to assign a value to an enum? [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 3 years ago.
Trying to assign a value to the _cat.CatType.
I was wondering how to do this without getting a null reference error?
using System;
public class Program
{
private CatClass _cat;
public void Main()
{
_cat.CatType = CatType.Active;
Console.WriteLine(_cat.CatType.ToString());
}
public enum CatType
{
New,
Active,
Inactive
}
public class CatClass
{
public CatType CatType
{
get;
set;
}
}
}
Ideally I want to assign it something like this _cat.CatType = CatType.Active
You need to initialise it with the new keyword
Used to create objects and invoke constructors
public void Main()
{
_cat = new CatClass();
_cat.CatType = CatType.Active;
Console.WriteLine(_cat.CatType.ToString());
}
You need to create an instance of the class.
private CatClass _cat = new CatClass;
Instantiate _cat with the new keyword first:
_cat = new CatClass
{
CatType = CatType.Active
};

Restrict access to property from outside the class [duplicate]

This question already has answers here:
IEnumerable vs IReadonlyCollection vs ReadonlyCollection for exposing a list member
(5 answers)
Closed 3 years ago.
Let's have this class:
ExampleClass
{
public List<string> MyValue { get; set; }
}
The question is how to restrict outside classes to modify of that property, means add object to collection, make new().
you can have something like this
public ReadOnlyCollection<string> MyValue {get; private set;}
You could expose it as IEnumerable<string> instead of as a list. This interface will not allow adds. You can still store it as a list internally, as a private field, so that the class itself can add or remove if needed.
For example:
class ExampleClass
{
private List<string> _myValue = new List<string>();
public IEnumerable<string> MyValue
{
get
{
foreach (var s in _myValue) yield return s;
}
}
}
If the caller would like to work with its own list, it can of course do this:
var list = exampleClass.MyValue.ToList();
At which point the caller owns it and it is clear that anything it chooses to add has nothing to do with the original list.

i am trying to pass values to an array in another class [duplicate]

This question already has answers here:
How do define get and set for an array data member?
(9 answers)
Closed 6 years ago.
i am trying to pass values to an array in another class
this is an example of what i am trying to do in detail:
public class CustomString
{
private string[] StringToAppend;
public string[] StringToAppend1
{
get
{
return StringToAppend;
}
set
{
StringToAppend = value;
}
}
public Class Form1:Form
{
CustomString strng1 = new CustomString();
strng1.StringToAppend1 = {"sssf","vfdr";} //Fails to compile Here
}
strng1.StringToAppend1 = {"sssf","vfdr";} //Fails to compile Here
That is the incorrect syntax for initialising a string array
strng1.StringToAppend1 = new[]{"sssf","vfdr"} ;
Above is the correct syntax.

C# Linq unique not work on lists [duplicate]

This question already has answers here:
Distinct() doesn't work
(4 answers)
Closed 7 years ago.
I am trying with the following code to check if a list contains duplicated data:
internal class Program
{
private static void Main(string[] args)
{
var list = new List<Obj>() { new Obj() { id = "1", name = "1" }, new Obj() { id = "1", name = "1" } };
Console.WriteLine(AllItemsAreUnique(list));
}
public static bool AllItemsAreUnique<T>(IEnumerable<T> items)
{
return items.Distinct().Count() == items.Count();
}
}
internal class Obj
{
public string id;
public string name;
}
And the result is true! Why?
Why?
By default, the comparison will use references and in this case, the two object references are not the same.
You need to implement IEquatable<T> to provide a type-specific Equals() method for Distinct() to use.

Categories