Implement a modified Stack [closed] - c#

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed last month.
Improve this question
Implement a modified stack that stores two color values โ€‹โ€‹(red and black) and supports the following operations:
void Push(value, color) - push the value (value) of the color (color) to the top of the stack.
value Pop() - remove the top element from the top of the stack and return its value (if the stack is empty, return null).
value FindLastByColor(color) - find the topmost value of the color (color) on the stack without removing this element from the stack (if there are no elements of this color on the stack, return null).

If the stack can hold values โ€‹โ€‹of different types, there will be no need to write a generic stack class (MyStack). Based on this assumption, the stack class that meets its needs can be designed as follows.
This is definition of my helper objects
public enum MyColor
{
Red,
Black
}
public class Item
{
public MyColor Color { get; }
public object Obj { get; }
public Item(MyColor color, object obj)
{
Color = color;
Obj = obj;
}
}
And this is CustomStack class
public class MyStack
{
private readonly Stack<Item> _items;
public MyStack()
{
_items = new Stack<Item>();
}
public void Push(MyColor color, object value)
{
_items.Push(new Item(color, value));
}
public object? Pop()
{
return _items.TryPop(out Item? item) ? item.Obj : null;
}
public object? FindLastByColor(MyColor myColor)
{
var item = _items.FirstOrDefault(i => i.Color == myColor);
return item?.Obj;
}
}

Related

C# Application Settings. A quick Question about User V's Application Scope [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 months ago.
The community is reviewing whether to reopen this question as of 7 months ago.
Improve this question
I have just looked at an example from Microsoft Social Network on how to use Application Settings namely this one:
public bool IsUSer(SettingsProperty Setting)
{
bool flag = Setting.Attributes[typeof(UserScopedSettingAttribute)] is UserScopedSettingAttribute;
bool flag1 = Setting.Attributes[typeof(ApplicationScopedSettingAttribute)] is ApplicationScopedSettingAttribute;
if (flag && flag2)
{
throw new ConfigurationErrorsException(SR.GetString("BothScopeAttributes"));
}
if (!flag && !flag2)
{
throw new ConfigurationErrorsException(SR.GetString("NoScopeAttributes"));
}
return flag;
}
This checks to see if the Setting is both User and Application Scoped or neither. Is it even possible that these two situations can occur. Surely the API would not allow this to happen in the first place. Should we be checking for this or is this example a little over the top. I know this is more a discussional rant but really, surely this can't really happen?
Link to Example: https://social.msdn.microsoft.com/Forums/en-US/4c0d2eae-2f0b-41c8-bb60-c4b0ffd3cd0b/how-to-retrieve-usersettings-v-defaultsettings-c-vbe2008?forum=netfxbcl
Thanks
Danny
[UserScopedSetting] and [ApplicationScopedSetting] are attributes so you might use them like this:
public class MyUserSettings : ApplicationSettingsBase
{
[UserScopedSetting()]
[DefaultSettingValue("white")]
public Color BackgroundColor
{
get
{
return ((Color)this["BackgroundColor"]);
}
set
{
this["BackgroundColor"] = (Color)value;
}
}
}
(Source for above code)
If you refer to this question, you'll see that it isn't possible to prevent two attributes occurring together. So, the code you have shown is actually protecting against one of these two scenarios:
1 - Both attributes are applied:
public class MyUserSettings : ApplicationSettingsBase
{
[UserScopedSetting()]
[ApplicationScopedSetting()]
[DefaultSettingValue("white")]
public Color BackgroundColor
{
get
{
return ((Color)this["BackgroundColor"]);
}
set
{
this["BackgroundColor"] = (Color)value;
}
}
}
2 - Neither attribute is applied:
public class MyUserSettings : ApplicationSettingsBase
{
[DefaultSettingValue("white")]
public Color BackgroundColor
{
get
{
return ((Color)this["BackgroundColor"]);
}
set
{
this["BackgroundColor"] = (Color)value;
}
}
}
So ultimately it is checking that exactly one of these two attributes is applied.

Multi-methods with multi-parameters or one method with object parameter [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 4 years ago.
Improve this question
Consider the following; I have a class with X and Y variables. the Idea of class is to change the position of points in both X axis and Y axis . I made a three methods in the first place for this purpose as :
the first one is to chage to X position
the second to change the Y position
the third one is to change both X and Y by passing on object for this class
The Code as
public class ChangePosition
{
public int X_AxisPosition;
public int Y_AxisPosition;
public ChangePosition(int X_Axis,int Y_Axis)
{
this.X_AxisPosition = X_Axis;
this.Y_AxisPosition = Y_Axis;
}
public void ChangeXAxisPosition(int XValue)
{
X_AxisPosition = XValue;
}
public void ChangeYAxisPosition(int YValue)
{
Y_AxisPosition = YValue;
}
public void ChangeXAxis_YAxisValues(ChangePosition NewLocaltion)
{
if (NewLocaltion == null)
{
X_AxisPosition = default;
Y_AxisPosition = default;
throw new NullReferenceException("Invalid Inputs");
}
ChangeXAxisPosition(NewLocaltion.X_AxisPosition);
}
}
After a while i rethinking and said why do i have two method in above (For Only either Axles), I could have the last one by passing on object form this class and set the unneeded Axis to zero as the following block showing U
public class ChangePosition
{
public int X_AxisPosition;
public int Y_AxisPosition;
public ChangePosition(int XValue, int YValue)
{
X_AxisPosition = XValue;
Y_AxisPosition = YValue;
}
public void ChangeXAxis_YAxisValues(ChangePosition NewLocaltion)
{
if (NewLocaltion == null)
{
throw new NullReferenceException("Invalid Inputs");
}
X_AxisPosition =(NewLocaltion.X_AxisPosition);
Y_AxisPosition =(NewLocaltion.Y_AxisPosition);
}
}
Could someone told me in term of best practices which of the previous code block is better? and Why?
The best practice for such entities as "position" or "vector" is to make them immutable - because its identity depends only on its state. It means that two ChangePosition objects, initialized with same X_AxisPosition and Y_AxisPosition are equal. So, whenever you want to change a field of immutable enitity, you always can simply replace the whole object. The fact that two points with the same state may be considered as different entities in your code may lead you into troubles.
In your case, public void ChangeXAxis_YAxisValues(ChangePosition NewLocaltion) doesn't make sense, since whenever you could use it like
someObject.Position.ChangeXAxis_YAxisValues(new ChangePosition(x, y));
you should better write
someObject.Position = new ChangePosition(x, y);
A common practice for points/positions is to use struct, struct is actually mutable, but its identity is represented with its state (struct's with same values of fields are equal, but not classes). It is also good to make its fields readonly, if it doesn't slow performance significantly.
So, keep it simple:
public struct ChangePosition
{
public int X_AxisPosition;
public int Y_AxisPosition;
public ChangePosition(int X_Axis,int Y_Axis)
{
this.X_AxisPosition = X_Axis;
this.Y_AxisPosition = Y_Axis;
}
}
Also, normally you may find useful to implement + operator.

Leave the type of a List in a class vague until populated [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
In a user-defined class, I'd like to leave the type of a List ambiguous so that I could have a list of strings or integers or tuples in separate instances of the class (that is to say, each list would be of only one type, but different instances of the class would different types). I currently have something like:
public Result
{
private List<dynamic> _vaguelist;
public List<dynamic> vaguelist {
get
{
return _vaguelist;
}
set
{
_vaguelist = value;
}
}
}
But, I'm pretty sure I'm not using the dynamic type properly. I think I would need a constructor that creates a new List where T gets determined from the GetType() of the first value added to the Class. Or write the List to be designated a certain type when it is initialized.
In short, how can I define a list within a class such that the type of its values can either be inherent of whatever is added to the list or specified when the class is instantiated? (values within a single list will all be of ONE type).
I think you have two options, the first one beign the best approach, will only work if you know the list will be of a certain type.
public class Result<T>
{
private List<T> _vaguelist = new List<T>();
public List<T> vaguelist {
get
{
return _vaguelist;
}
set
{
_vaguelist = value;
}
}
}
Result a = new Result<string>();
a.vaguelist.Add("1234");
Result b = new Result<int>();
a.vaguelist.Add(1234);
The second option will work if you wan't to add more than one type into the list o you won't know what you're putting into the list
public class Result
{
private List<object> _vaguelist;
public List<object> vaguelist {
get
{
return _vaguelist;
}
set
{
_vaguelist = value;
}
}
}
Result a = new Result();
a.vaguelist.Add("1234");
a.vaguelist.Add(1234);
The problem with this approach is that you will have to cast every single item in the list in order to take advantage of the type the item is.
Making use of the first approach, you could implement it like this:
public class Result<T>
{
private List<T> _vaguelist = new List<T>();
public List<T> vaguelist {
get
{
return _vaguelist;
}
set
{
_vaguelist = value;
}
}
}
public abstract class Result
{
public static Result<T> NewResultFromItem<T>(T item)
{
Result<T> result = new Result<T>();
result.vaguelist.Add(item);
return result;
}
}
string item1 = "123";
string item2 = "234";
var result = Result.NewResultFromItem(item1);
result.vaguelist.Add(item2);
You are asking for both type safety and type agnosticism (I just made up that word), which you cannot have both at the same time. Suppose you would find a way to make the list flip to a type safe collection at runtime when the first item is added. Who or what would be able to use it as such if you cannot code against it? The compiler will not know what it is going to be at runtime so there is not much that can be done for type safety. At runtime you would still have to figure out what you are dealing with so from a coding perspective it would still be just a list of objects.

How to check how many times a class property was set with a specific value? [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 7 years ago.
Improve this question
Is there any possible way in determining how many times a class property was set with a specific value ?
You can do it by using settter as well, Lake a look into the following snippet
class myClass
{
private string _MyStringVar;
public string specificWord = "word";
public int SpecificCount = 0;
public string MyStringVar
{
get { return _MyStringVar; }
set
{
bool isChanged = false;
if (_MyStringVar != specificWord) { isChanged = true; }
// check for old value to confirm value changed
_MyStringVar = value;
if (value == specificWord && isChanged) { SpecificCount++; }
}
}
}
you can implement INotifyPropertyChanged for this purpose
Source: https://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged(v=vs.110).aspx

Let the user edit some value,but not all [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
I am writing a sudoko program, I want the user to edit certain values in the array,but not the values which are already there. how do I initialize the array?
The easiest way to overcome your problem is to use 2 multidimensional arrays, the first one to save the value and the second one to check whether some cell can be edited by the user or not..
int[,] ValueArray= new int[4,4];
boolean[,] EditedArray= new boolean[4,4];
You can approach your problem with multiple solutions, all of which relay on the same principle -> Having your number coupled with a boolean.
You can write it down with a class:
public class SudokuCell
{
public bool IsEditable { get; set; }
private int _value;
public int Value
{
get { return _value; }
set { if (IsEditable) _value = value; }
}
or a struct:
public struct SudokuCell
{
public bool IsEditable;
public int Value;
}
and have a List or an Array of SudokuCells that you can use as your data structure or you can use a lazier method and write it down using Tuple:
List<Tuple<int, bool>> sudokuCells = new List<Tuple<int,bool>>();
Then whenever you want to change the value you can check it's corresponding bool and you instantly know whether you can or can't change it (assuming you set it when you initialize your sudoku)
Your sudoku user edits your UI, not your array. Make the UI element read-only when the associated data should be read-only.

Categories