I am having a problem about structures. I am trying to calculate quadrengles parameter, area and whether it is square or not but code doesn't go to if else part of islem();. This is my homework about struct.
using System;
public struct Str
{
private double val;
public double Value
{
get { return val; }
set { val = value; }
}
public double Oku()
{
return double.Parse(Console.ReadLine());
}
}
public struct Dörtgen
{
Str ak;
Str bk;
public Str Ake
{
get { return ak; }
set { ak = value; }
}
public Str Bke
{
get { return bk; }
set { bk = value; }
}
public void Dörtgen1()
{
Str rct = new Str();
Console.WriteLine("\nenter sides a and be of the square: ");
Console.Write("A side: ");
ak.Value = rct.Oku();
Console.Write("B side: ");
bk.Value = rct.Oku();
}
public void İslem()
{
Console.WriteLine("parameter: {0}", (Ake.Value + Bke.Value) * 2);
Console.WriteLine("area: {0}\n", Ake.Value * Bke.Value);
if (Ake.Value == Bke.Value)
{
Console.WriteLine("this is a square");
}
else if (Ake.Value == Bke.Value)
{
Console.WriteLine("this is not a square");
}
}
}
public class Program
{
static void Main()
{
var drg = new Dörtgen();
drg.Dörtgen1();
Console.WriteLine();
Console.WriteLine("parameter and area");
drg.İslem();
}
}
if (Ake.Value == Bke.Value)
{
Console.WriteLine("this is a square");
}
else if (Ake.Value == Bke.Value)
{
Console.WriteLine("this is not a square");
}
Should be:
// Sides are equal: it's a square
if (Ake.Value == Bke.Value)
{
Console.WriteLine("this is a square");
}
// didn't enter the "square" branch, so it's not a square
else
{
Console.WriteLine("this is not a square");
}
Explanation: Besides the fact that you wrote Ake.Value == Bke.Value in both if and else if, you don't actually need to check anything if the first if is false, you can just go to the else branch.
Related
I have the code shown here, and I would like to make a Interactive NPC.
Basically end the player was like next to the NPC/letter, the player would be able to interact with it either by pressing a key for example "E" or just by being close to it and show some text in the console.
How could I do it? I'm new to C# so I don't have much knowledge about it. If anyone has any tutorial or could explain with coding I would appreciate it.
The code is:
namespace SoulfulDungeon
{
class World
{
private string[,] Grid;
private int Rows;
private int Cols;
public World(string[,] grid)
{
Grid = grid;
Rows = Grid.GetLength(0);
Cols = Grid.GetLength(1);
}
public void Draw()
{
for (int y = 0; y < Rows; y++)
{
for (int x = 0; x < Cols; x++)
{
string element = Grid[y, x];
Console.SetCursorPosition(x, y);
Console.Write(element);
}
}
}
public string GetElementAt(int x, int y)
{
return Grid[y, x];
}
public string Trap(int x, int y)
{
return Grid[y, x];
}
public bool IsPositionWalkable(int x, int y)
{
//Verificar Limites
if (x < 0 || y < 0 || x >= Cols || y >= Rows)
{
return false;
}
if (Lever.LeverMarker == "K")
{
return Grid[y, x] == "(" || Grid[y, x] == " " || Grid[y, x] == "X" || Grid[y, x] == "T";
}
else if(Lever.LeverMarker != "K")
{
//Verificar locais de passagem
return Grid[y, x] == " " || Grid[y, x] == "X" || Grid[y, x] == "T";
}
return false;
}
}
public class SwitchDeath //metodo escolhas switch
{
public static int Variavel1;
public static int Variavel2;
public static void Choices()
{
bool Key = false; //escolha através de keys
do
{
ConsoleKeyInfo keyReaded = Console.ReadKey(true);
switch (keyReaded.Key)
{
case ConsoleKey.Q:
Variavel1 = 1;
Key = true;
Console.WriteLine("You pulled the lever");
break;
case ConsoleKey.E:
Variavel2 = 1;
Key = true;
Console.WriteLine("You turned on the switch... a rain of arrows fell in your head...");
break;
default:
Console.WriteLine("You chose to stay still... The darkness consumed you and your conscience was washed away");
Variavel2 = 1;
Key = true;
break;
}
} while(!Key);
if (Variavel1 == 1)
{
Console.WriteLine("The room");
}
if (Variavel2 == 1)
{
Console.WriteLine("you died");
Environment.Exit(0);
}
}
}
class Variables
{
public int X { get; set;}
public int Y { get; set;}
public static string? EnemyMarker;
public static ConsoleColor EnemyColor;
public static string? PlayerMarker;
public static ConsoleColor PlayerColor;
public static string? LeverMarker;
public static ConsoleColor LeverColor;
public static string? DoorMarker;
}
class Player : Variables
{
public Player( int initialX, int initialY)
{
X = initialX;
Y = initialY;
PlayerMarker = "0";
PlayerColor = ConsoleColor.Blue;
}
public void Draw()
{
Console.ForegroundColor = PlayerColor;
Console.SetCursorPosition(X, Y);
Console.Write(PlayerMarker);
Console.ResetColor();
}
}
class Enemy : Variables
{
public Enemy( int initialX, int initialY)
{
X = initialX;
Y = initialY;
EnemyMarker = "5";
EnemyColor = ConsoleColor.Red;
}
public void Draw()
{
Console.ForegroundColor = EnemyColor;
Console.SetCursorPosition(X, Y);
Console.Write(EnemyMarker);
Console.ResetColor();
}
}
class Lever : Variables
{
public Lever( int initialX, int initialY)
{
X = initialX;
Y = initialY;
LeverMarker = "k";
LeverColor = ConsoleColor.Yellow;
}
public void Draw()
{
Console.ForegroundColor = LeverColor;
Console.SetCursorPosition(X, Y);
Console.Write(LeverMarker);
Console.ResetColor();
}
}
class Door : Variables
{
public Door( int initialX, int initialY)
{
X = initialX;
Y = initialY;
DoorMarker = " ";
}
public void Draw()
{
Console.SetCursorPosition(X, Y);
Console.Write(DoorMarker);
}
}
class Program
{
private static World? MyWorld;
private static Player? CurrentPlayer;
private static Enemy? CurrentEnemy;
private static Lever? CurrentLever;
private static Door? CurrentDoor;
public static void Main(string[] args)
{
Console.CursorVisible = false;
Console.WriteLine("You found a lever and a switch :O");
System.Threading.Thread.Sleep(150);
Console.WriteLine("Choose: Press 'Q' to pull the lever | Press 'E' to turn the switch");
SwitchDeath.Choices();
string [,] grid = LevelParser.ParseFileToArray("Level0.txt");
MyWorld = new World(grid);
CurrentPlayer = new Player(0, 5);
//CurrentEnemy = new Enemy(2, 1);
CurrentLever = new Lever (11, 3);
CurrentDoor = new Door (11, 6);
RunGameLoop();
}
private static void DrawFrame()
{
Console.Clear();
MyWorld!.Draw();
CurrentPlayer!.Draw();
CurrentLever!.Draw();
if (Lever.LeverMarker == "K")
{
CurrentDoor!.Draw();
CurrentPlayer!.Draw();
CurrentLever!.Draw();
}
}
class Detection
{
public static void DetectionLever()
{
if (CurrentPlayer is not null)
if (CurrentLever is not null)
if (CurrentPlayer.Y == CurrentLever.Y)
{
if (CurrentPlayer.X == CurrentLever.X)
{
Lever.LeverMarker = "K";
Lever.LeverColor = ConsoleColor.DarkYellow;
}
}
}
public static void DetectionEnemy()
{
if (CurrentPlayer is not null)
if (CurrentEnemy is not null)
if (CurrentPlayer.Y == CurrentEnemy.Y)
{
if (CurrentPlayer.X == CurrentEnemy.X)
{
Console.Clear();
Console.WriteLine("You died... Don't touch the ghouls...");
CurrentPlayer = new Player(0, 5);
CurrentPlayer!.Draw();
}
}
}
}
private static void HandlePlayerInput()
{
ConsoleKeyInfo keyInfo = Console.ReadKey(true);
ConsoleKey key = keyInfo.Key;
if (MyWorld is not null)
if (CurrentPlayer is not null)
switch (key)
{
case ConsoleKey.UpArrow:
if (MyWorld.IsPositionWalkable(CurrentPlayer.X, CurrentPlayer.Y - 1))
{
CurrentPlayer.Y -= 1;
}
break;
case ConsoleKey.DownArrow:
if (MyWorld.IsPositionWalkable(CurrentPlayer.X, CurrentPlayer.Y + 1))
{
CurrentPlayer.Y += 1;
}
break;
case ConsoleKey.LeftArrow:
if (MyWorld.IsPositionWalkable(CurrentPlayer.X - 1 , CurrentPlayer.Y))
{
CurrentPlayer.X -= 1;
}
break;
case ConsoleKey.RightArrow:
if (MyWorld.IsPositionWalkable(CurrentPlayer.X + 1, CurrentPlayer.Y))
{
CurrentPlayer.X += 1;
}
break;
case ConsoleKey.E:
Console.Clear();
Environment.Exit(0);
break;
default:
break;
}
}
private static void RunGameLoopEnemy()
{
if (MyWorld is not null)
if(CurrentPlayer is not null)
while(true)
{
DrawFrame();
HandlePlayerInput();
Detection.DetectionLever();
Detection.DetectionEnemy();
string elementAtPlayerPros = MyWorld.GetElementAt(CurrentPlayer.X, CurrentPlayer.Y);
if (elementAtPlayerPros == "X")
{
Console.Clear();
break;
}
string Traps = MyWorld.Trap(CurrentPlayer.X, CurrentPlayer.Y);
if (Traps == "T")
{
Console.Clear();
break;
}
System.Threading.Thread.Sleep(20);
}
}
private static void RunGameLoop()
{
if (MyWorld is not null)
if(CurrentPlayer is not null)
while(true)
{
DrawFrame();
HandlePlayerInput();
Detection.DetectionLever();
string elementAtPlayerPros = MyWorld.GetElementAt(CurrentPlayer.X, CurrentPlayer.Y);
if (elementAtPlayerPros == "X")
{
Console.Clear();
break;
}
string Traps = MyWorld.Trap(CurrentPlayer.X, CurrentPlayer.Y);
if (Traps == "T")
{
Console.Clear();
break;
}
System.Threading.Thread.Sleep(20);
}
}
}
}
Didn't try anything yet because I don't really know how I could do it
I'm new using C# and I'm building a remote control. I got stuck and my code is not compiling. Please I need suggestions and how can I improve my code.
I think its Console.Readline() but I'm not sure how to use it. Also how can change this to 2 primary classes?
public class testRemote
{
public static bool PowerOn(bool powerStatus)
{
if (powerStatus == true)
{
testRemote.DisplayMessage("TV already on");
}
else
{
powerStatus = true;
testRemote.DisplayMessage("TV On, Your Channel is 3 and the Volume is 5");
}
return powerStatus;
}
public static bool PowerOff(bool powerStatus)
{
if (powerStatus == false)
{
testRemote.DisplayMessage("TV already off");
}
else
{
powerStatus = false;
testRemote.DisplayMessage("TV is now off");
}
return powerStatus;
}
public static int VolumeUp(bool powerStat, int vol)
{
if (powerStat == false)
{
testRemote.DisplayMessage("TV is off");
}
else
{
if (vol >= 10)
{
testRemote.DisplayMessage("TV is already on Maximum Volume.");
}
else
{
vol++;
if (vol == 10)
{
testRemote.DisplayMessage("Maximum Volume.");
}
}
}
return vol;
}
public static int VolumeDown(bool powerStat, int vol)
{
if (powerStat == false)
{
testRemote.DisplayMessage("TV is off");
}
else
{
if (vol <= 0)
{
testRemote.DisplayMessage("Sound Muted");
}
else
{
vol--;
if (vol == 0)
{
testRemote.DisplayMessage("Sound Muted");
}
}
}
return vol;
}
public static int ChannelUp(bool powerStat, int channelNo)
{
if (powerStat == false)
{
testRemote.DisplayMessage("TV is off");
}
else
{
if (channelNo < 99)
{
channelNo++;
}
else
{
channelNo = 2;
}
Console.WriteLine("Channel " + channelNo.ToString());
}
return channelNo;
}
public static int ChannelDown(bool powerStat, int channelNo)
{
if (powerStat == false)
{
testRemote.DisplayMessage("TV is off");
}
else
{
if (channelNo == 2)
{
channelNo = 99;
}
else
{
channelNo--;
}
Console.WriteLine("Channel " + channelNo.ToString());
}
return channelNo;
}
public static String SmartMenu(bool powerStat, String md)
{
if (powerStat == false)
{
testRemote.DisplayMessage("TV is off");
}
else
{
testRemote.DisplayMessage("Smart Menu On");
md = "TV";
}
return md;
}
public static String SetSettings(bool powerStat, String md)
{
if (powerStat == false)
{
testRemote.DisplayMessage("TV is off");
}
else
{
testRemote.DisplayMessage("Settings On");
md = "Settings";
}
return md;
}
public static void DisplayMessage(String msg)
{
Console.WriteLine(msg);
}
public static void Banner()
{
Console.WriteLine("Welcome to TV Remote Control");
Console.WriteLine("Please enter your selection");
Console.WriteLine("Power On - turns on your TV");
Console.WriteLine("Power Off - turns off your TV");
Console.WriteLine("Increase volume - turns up the volume");
Console.WriteLine("Decrease volume - turn down the volume");
Console.WriteLine("Channel Up - increments the channel");
Console.WriteLine("Channel Down - decrements the channel");
Console.WriteLine("Smart Menu");
Console.WriteLine("Settings");
Console.WriteLine();
Console.WriteLine("Please enter your selection");
}
public static void Main(String[] args)
{
bool powerOn = false;
int channel = 3;
int volume = 5;
string mode = "TV";
string choice = "Turn On";
string c = Console.ReadLine();
while (choice.ToLower().Equals("Exit".ToLower()) != true)
{
if (choice.ToLower().Equals("Power On".ToLower()) == true)
{
powerOn = testRemote.PowerOn(powerOn);
}
if (choice.ToLower().Equals("Power Off".ToLower()) == true)
{
powerOn = testRemote.PowerOff(powerOn);
}
if (choice.ToLower().Equals("Increase volume".ToLower()) == true)
{
volume = testRemote.VolumeUp(powerOn, volume);
}
if (choice.ToLower().Equals("Decrease volume".ToLower()) == true)
{
volume = testRemote.VolumeDown(powerOn, volume);
}
if (choice.ToLower().Equals("Channel Up".ToLower()) == true)
{
channel = testRemote.ChannelUp(powerOn, channel);
}
if (choice.ToLower().Equals("Channel Down".ToLower()) == true)
{
channel = testRemote.ChannelDown(powerOn, channel);
}
if (choice.ToLower().Equals("Mode TV".ToLower()) == true)
{
mode = testRemote.SmartMenu(powerOn, mode);
}
if (choice.ToLower().Equals("Mode DVD".ToLower()) == true)
{
mode = testRemote.SetSettings(powerOn, mode);
}
Console.WriteLine();
Console.WriteLine();
choice = Console.ReadLine();
}
Console.WriteLine("Thank you for the Remote Controller");
Console.ReadLine();
}
}
Since the question is not clear i slightly modified your code, it compiles and runs BUT needs a lot of refactor.
Here is the working code.
using System;
namespace TvRemote
{
public class testRemote
{
public static bool PowerOn(bool powerStatus)
{
if (powerStatus == true)
{
testRemote.DisplayMessage("TV already on");
}
else
{
powerStatus = true;
testRemote.DisplayMessage("TV On, Your Channel is 3 and the Volume is 5");
}
return powerStatus;
}
public static bool PowerOff(bool powerStatus)
{
if (powerStatus == false)
{
testRemote.DisplayMessage("TV already off");
}
else
{
powerStatus = false;
testRemote.DisplayMessage("TV is now off");
}
return powerStatus;
}
public static int VolumeUp(bool powerStat, int vol)
{
if (powerStat == false)
{
testRemote.DisplayMessage("TV is off");
}
else
{
if (vol >= 10)
{
testRemote.DisplayMessage("TV is already on Maximum Volume.");
}
else
{
vol++;
if (vol == 10)
{
testRemote.DisplayMessage("Maximum Volume.");
}
}
}
return vol;
}
public static int VolumeDown(bool powerStat, int vol)
{
if (powerStat == false)
{
testRemote.DisplayMessage("TV is off");
}
else
{
if (vol <= 0)
{
testRemote.DisplayMessage("Sound Muted");
}
else
{
vol--;
if (vol == 0)
{
testRemote.DisplayMessage("Sound Muted");
}
}
}
return vol;
}
public static int ChannelUp(bool powerStat, int channelNo)
{
if (powerStat == false)
{
testRemote.DisplayMessage("TV is off");
}
else
{
if (channelNo < 99)
{
channelNo++;
}
else
{
channelNo = 2;
}
Console.WriteLine("Channel " + channelNo.ToString());
}
return channelNo;
}
public static int ChannelDown(bool powerStat, int channelNo)
{
if (powerStat == false)
{
testRemote.DisplayMessage("TV is off");
}
else
{
if (channelNo == 2)
{
channelNo = 99;
}
else
{
channelNo--;
}
Console.WriteLine("Channel " + channelNo.ToString());
}
return channelNo;
}
public static String SmartMenu(bool powerStat, String md)
{
if (powerStat == false)
{
testRemote.DisplayMessage("TV is off");
}
else
{
testRemote.DisplayMessage("Smart Menu On");
md = "TV";
}
return md;
}
public static String SetSettings(bool powerStat, String md)
{
if (powerStat == false)
{
testRemote.DisplayMessage("TV is off");
}
else
{
testRemote.DisplayMessage("Settings On");
md = "Settings";
}
return md;
}
public static void DisplayMessage(String msg)
{
Console.WriteLine(msg);
}
public static void Banner()
{
Console.WriteLine("Welcome to TV Remote Control");
Console.WriteLine("Please enter your selection");
Console.WriteLine("Power On - turns on your TV");
Console.WriteLine("Power Off - turns off your TV");
Console.WriteLine("Increase volume - turns up the volume");
Console.WriteLine("Decrease volume - turn down the volume");
Console.WriteLine("Channel Up - increments the channel");
Console.WriteLine("Channel Down - decrements the channel");
Console.WriteLine("Smart Menu");
Console.WriteLine("Settings");
Console.WriteLine();
Console.WriteLine("Please enter your selection");
}
public static void Main(String[] args)
{
bool powerOn = false;
int channel = 3;
int volume = 5;
string mode = "TV";
//string choice = "Turn On"; //THIS MUST BE Power On if you want to power on the tv as soon as the app is launched
Banner();
string choice = Console.ReadLine();
while (!choice.ToLower().Equals("Exit".ToLower()))
{
if (choice.ToLower().Equals("Power On".ToLower()) == true)
{
powerOn = testRemote.PowerOn(powerOn);
}
if (choice.ToLower().Equals("Power Off".ToLower()) == true)
{
powerOn = testRemote.PowerOff(powerOn);
}
if (choice.ToLower().Equals("Increase volume".ToLower()) == true)
{
volume = testRemote.VolumeUp(powerOn, volume);
}
if (choice.ToLower().Equals("Decrease volume".ToLower()) == true)
{
volume = testRemote.VolumeDown(powerOn, volume);
}
if (choice.ToLower().Equals("Channel Up".ToLower()) == true)
{
channel = testRemote.ChannelUp(powerOn, channel);
}
if (choice.ToLower().Equals("Channel Down".ToLower()) == true)
{
channel = testRemote.ChannelDown(powerOn, channel);
}
if (choice.ToLower().Equals("Mode TV".ToLower()) == true)
{
mode = testRemote.SmartMenu(powerOn, mode);
}
if (choice.ToLower().Equals("Mode DVD".ToLower()) == true)
{
mode = testRemote.SetSettings(powerOn, mode);
}
Console.WriteLine();
Console.WriteLine();
choice = Console.ReadLine();
}
Console.WriteLine("Thank you for the Remote Controller");
Console.ReadLine();
}
}
}
I have a little helper class that generates a script, used later in my code, namely :
public class ScriptBuilder
{
public string Script { get; set; }
public ScriptBuilder NewLine(uint numberOfLines = 1)
{
if (numberOfLines == 0)
{
return this;
}
else
{
for (int i = 1; i <= numberOfLines; ++i)
{
Script += Environment.NewLine;
}
return this;
}
}
public ScriptBuilder WriteLine(string str = "")
{
if (str != "")
{
Script += str;
NewLine();
}
return this;
}
public ScriptBuilder(string line = "")
{
Script = line;
if (line != "")
{
NewLine();
}
}
public ScriptBuilder setLong(string longName, long x)
{
WriteLine("int " + longName + " " + x.ToString(System.Globalization.CultureInfo.InvariantCulture));
return this;
}
// + other set functions with different parameters/numbers of parameters
}
// ScriptBuilder is used like this :
ScriptBuilder scriptStringBuilder = new ScriptBuilder();
scriptStringBuilder
.WriteLine($"/!HEADSTART")
.WriteLine($"/! TYPE = {scriptType}")
.WriteLine($"/! NAME = {name}")
.WriteLine($"/! DESCRIPTION = {description}")
.WriteLine($"/!HEADEND")
/* the header is done now */
.NewLine(2);
It is pretty basic method chaining. I would like to implement IF and IF ELSE IF ELSE in this scripting language, but I don't see a really neat way for doing it.
For the IF I came up with the member function :
public ScriptBuilder IF(bool condition, ScriptBuilder res)
{
if (condition)
{
return res;
}
else
{
return this;
}
}
that can be used as :
ScriptBuilder.IF(condition,
scriptStringBuilder
.setThis(...)
.setThat(...)
;
)
but I am not satisfied because
scriptStringBuilder.setThis(...).setThat(...); would alread have taken effect
I have to write scriptStringBuilder to use it. No pertinent idea of the IF ELSE IF ELSE though.
I could use delegates perhaps, like :
public delegate ScriptBuilder ScriptBuilderFunction(params object[] Parameters);
public ScriptBuilder IF(bool condition, ScriptBuilderFunction func)
{
// ...
}
but I don't even see how to implement that ...
Ideally, I would like to write :
scriptStringBuilder.
.setThis(...)
.setThat(...)
.IF(condition)
.THEN()
.setThis(...)
.doThat(...)
.ELSEIF(othercondition)
.makeThis(...)
.doThat(...)
.ENDIF()
.setThatNow(...)
;
This is a very rough sketch of how you could implement this:
class Program
{
static void Main(string[] args)
{
var number = 999;
ScriptBuilder scriptStringBuilder = new ScriptBuilder();
var text = scriptStringBuilder
.WriteLine($"/!HEADSTART")
.WriteLine($"/! TYPE = abc")
.WriteLine($"/! NAME = name")
.WriteLine($"/!HEADEND")
.NewLine(2)
.IfCondition(number != 999, ifCondition => {
ifCondition.NewLine(1);
ifCondition.WriteLine("SUCCESS");
}, elseCondition => {
elseCondition.NewLine(1);
elseCondition.WriteLine("FAIL");
},
elseIf1 => elseIf1.ElseIfCondition(number > 1, h1 => h1.WriteLine("NUMBER IS BIGGER THAN 1")),
elseIf2 => elseIf2.ElseIfCondition(number > 2, h2 => h2.WriteLine("NUMBER IS BIGGER THAN 2")))
.Build();
Console.WriteLine(text);
Console.ReadKey();
}
}
public class ScriptBuilder : IElseIfConditionable
{
private string _script;
public ScriptBuilder NewLine(uint numberOfLines = 1)
{
if (numberOfLines == 0)
{
return this;
}
else
{
for (int i = 1; i <= numberOfLines; ++i)
{
_script += Environment.NewLine;
}
return this;
}
}
public ScriptBuilder WriteLine(string str = "")
{
if (str != "")
{
_script += str;
NewLine();
}
return this;
}
public ScriptBuilder(string line = "")
{
_script = line;
if (line != "")
{
NewLine();
}
}
public ScriptBuilder SetLong(string longName, long x)
{
WriteLine("int " + longName + " " + x.ToString(System.Globalization.CultureInfo.InvariantCulture));
return this;
}
public string Build()
{
return _script;
}
public ScriptBuilder IfCondition(bool condition, Action<ScriptBuilder> trueCondition, Action<ScriptBuilder> falseCondition, params Func<IElseIfConditionable, Tuple<ScriptBuilder, bool>>[] elseIfs)
{
if (condition)
{
trueCondition(this);
return this;
}
foreach (var elseIf in elseIfs)
{
if (elseIf(this).Item2)
{
return this;
}
}
if (!condition)
{
falseCondition(this);
}
return this;
}
public Tuple<ScriptBuilder, bool> ElseIfCondition(bool condition, Action<ScriptBuilder> trueCondition)
{
if (condition)
{
trueCondition(this);
}
return Tuple.Create(this, condition);
}
}
public interface IElseIfConditionable
{
Tuple<ScriptBuilder, bool> ElseIfCondition(bool condition, Action<ScriptBuilder> trueCondition);
}
This is equivalent of:
var s = new ScriptBuilder();
if (number != 999)
{
s.NewLine(1);
s.WriteLine("SUCCESS");
}
else if (number > 1)
{
s.WriteLine("NUMBER IS BIGGER THAN 1");
}
else if (number > 2)
{
s.WriteLine("NUMBER IS BIGGER THAN 2");
}
else
{
s.NewLine(1);
s.WriteLine("FAIL");
}
I'm trying to create an e-ATM console app using C# using inheritance, but every time I debug I see that the derived class values are null, whereas the base class fields or properties are filled with values. Why is the derived class not showing the list with their data even after it is inherited from the base class?
class CreateAccount
{
string firstName, lastName, dateOfBirth, phoneNO, fathersName, mothersName;
double initialBalance; int pinNo = 100, accountNo = 1234, age; DateTime yearOfBirth;
protected static List<CreateAccount> data = new List<CreateAccount>();
protected string FirstName
{
get { return this.firstName; }
set
{
if (string.IsNullOrEmpty(value)) throw new Exception();
else firstName = value;
}
}
protected string LastName
{
get { return this.lastName; }
set
{
if (string.IsNullOrEmpty(value)) throw new Exception();
else lastName = value;
}
}
protected string DateOfBirth
{
get { return this.dateOfBirth; }
set
{
if (string.IsNullOrEmpty(value)) throw new Exception();
else dateOfBirth = value;
}
}
protected string PhoneNo
{
get { return this.phoneNO; }
set
{
if ((string.IsNullOrEmpty(value)) || value.Length != 10)
throw new Exception();
else
phoneNO = value;
}
}
protected string FathersName
{
get { return this.fathersName; }
set
{
if (string.IsNullOrEmpty(value))
throw new Exception();
else
fathersName = value;
}
}
protected string MothersName
{
get { return this.mothersName; }
set
{
if (string.IsNullOrEmpty(value))
throw new Exception();
else
mothersName = value;
}
}
protected double InititailBalance
{
get { return this.initialBalance; }
set
{
if (double.IsNaN(value))
throw new Exception();
else
initialBalance = value;
}
}
protected int PinNo
{
get { return this.pinNo; }
}
protected int AccountNo
{
get { return this.accountNo; }
}
public void GenerateAccount()
{
// code for asking user for their details.
data.Add(this);
}
}
class ATM :CreateAccount
{
public void Deposit()
{
Console.WriteLine("Enter your account number");
int accountNo = int.Parse(Console.ReadLine());
if (accountNo == AccountNo)
{
Console.WriteLine("Enter your amount you wish to deposit");
int amount = int.Parse(Console.ReadLine());
InititailBalance+= amount;
}
}
}
class Program
{
static void Main(string[] args)
{
while (true)
{
Console.WriteLine("Menu");
Console.WriteLine("1.Create Account");
Console.WriteLine("2.ATM");
Console.Write("Please enter your selections: ");
int select = int.Parse(Console.ReadLine());
switch (select)
{
case 1:
CreateAccount account = new CreateAccount();
account.GenerateAccount();
break;
case 2:
ATM atm = new ATM();
atm.Deposit();
break;
}
}
}
}
You are creating two different objects: a 'CreateAccount' Object and an 'ATM' object.
An ATM object does not automatically inherit the values from a previously created CreateAccount object, they are two completely different, unrelated entities.
So for your ATM object to have the same values that your CreateAccount object has, you would have to copy the CreateAccount object to your ATM object.
CreateAccount account = new CreateAccount();
//set account variables here
ATM atm = (ATM)account;
Here is how it's done with proper use of inheritance which is useless in this case actually. Dictionary is the proper datastructure to use in this case because you can avoid duplicates with it. Also from this code you might want to remove the accountNo from Account class to avoid duplicate numbers being kept and the ask it beffore calling GenerateAccount() method. So this is full console app:
using System;
using System.Collections.Generic;
using System.Linq;
namespace ATM
{
class Account
{
string firstName, lastName, dateOfBirth, phoneNO, fathersName, mothersName;
double initialBalance;
int pinNo, accountNo, age;
DateTime yearOfBirth;
public Account()
{
pinNo = 100;
accountNo = 1234;
}
public string FirstName
{
get { return this.firstName; }
set
{
if (string.IsNullOrEmpty(value)) throw new Exception();
else firstName = value;
}
}
public string LastName
{
get { return this.lastName; }
set
{
if (string.IsNullOrEmpty(value)) throw new Exception();
else lastName = value;
}
}
public string DateOfBirth
{
get { return this.dateOfBirth; }
set
{
if (string.IsNullOrEmpty(value)) throw new Exception();
else dateOfBirth = value;
}
}
public string PhoneNo
{
get { return this.phoneNO; }
set
{
if ((string.IsNullOrEmpty(value)) || value.Length != 10)
throw new Exception();
else
phoneNO = value;
}
}
public string FathersName
{
get { return this.fathersName; }
set
{
if (string.IsNullOrEmpty(value))
throw new Exception();
else
fathersName = value;
}
}
public string MothersName
{
get { return this.mothersName; }
set
{
if (string.IsNullOrEmpty(value))
throw new Exception();
else
mothersName = value;
}
}
public double InititailBalance
{
get { return this.initialBalance; }
set
{
if (double.IsNaN(value))
throw new Exception();
else
initialBalance = value;
}
}
public int PinNo
{
get { return this.pinNo; }
}
public int AccountNo
{
get { return this.accountNo; }
}
public void GenerateAccount()
{
// code for asking user for their details.
}
}
class ATM
{
public static Dictionary<int, Account> AccountsList;
static ATM()
{
AccountsList = new Dictionary<int, Account>();
}
public void CreateAccount()
{
Account acc = new Account();
acc.GenerateAccount();
AccountsList.Add(acc.AccountNo, acc);
}
public void Deposit()
{
Console.WriteLine("Enter your account number");
int accountNo = int.Parse(Console.ReadLine());
if (AccountsList.ContainsKey(accountNo))
{
Console.WriteLine("Enter your amount you wish to deposit");
int amount = int.Parse(Console.ReadLine());
AccountsList[accountNo].InititailBalance += amount;
}
}
}
class Program
{
static void Main(string[] args)
{
ATM atm = new ATM();
while (true)
{
Console.WriteLine("Menu");
Console.WriteLine("1.Create Account");
Console.WriteLine("2.ATM");
Console.Write("Please enter your selections: ");
int select = int.Parse(Console.ReadLine());
switch (select)
{
case 1:
atm.CreateAccount();
break;
case 2:
atm.Deposit();
break;
default:
Console.WriteLine("Invalid selection!");
break;
}
}
}
}
}
CreateAccount is an operation of Atm and this is why I don't think you should be using inheritance. I propose this solution:
Class Account:
class Account
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime DateOfBirth { get; set; }
public string PhoneNumber { get; set; }
public double Balance { get; set; }
// More properties here
...
}
Class Atm:
class Atm
{
public List<Account> Accounts { get; set; }
public Atm()
{
Accounts = new List<Account>();
}
public void CreateAccount()
{
var account = new Account();
// Get details from user here:
...
account.Balance = 0.0;
account.Id = Accounts.Count + 1;
Accounts.Add(account);
}
public void Deposit()
{
int accountId;
// Get input from the user here:
// --------------------------------
// 1. Check that the account exists
// 2. Deposit into the account.
...
}
Full example:
class Program
{
static void Main()
{
var atm = new Atm();
while (true)
{
int option;
Console.WriteLine();
Console.WriteLine("Menu:");
Console.WriteLine("1. Create Account");
Console.WriteLine("2. Deposit");
Console.WriteLine();
Console.Write("Please make a selection: ");
var input = int.TryParse(Console.ReadLine(), out option);
Console.WriteLine("-----------------");
switch (option)
{
case 1:
atm.CreateAccount();
break;
case 2:
atm.Deposit();
break;
}
}
}
}
class Account
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime DateOfBirth { get; set; }
public string PhoneNumber { get; set; }
public double Balance { get; set; }
}
class Atm
{
public List<Account> Accounts { get; set; }
public Atm()
{
Accounts = new List<Account>();
}
public void CreateAccount()
{
var account = new Account();
Console.WriteLine("Create a new account!");
Console.WriteLine();
Console.Write("Enter first name: ");
account.FirstName = Console.ReadLine();
Console.Write("Enter last name: ");
account.LastName = Console.ReadLine();
Console.Write("Enter date of birth: ");
account.DateOfBirth = DateTime.Parse(Console.ReadLine());
Console.Write("Enter phone number: ");
account.PhoneNumber = Console.ReadLine();
account.Balance = 0.0;
account.Id = Accounts.Count + 1;
Accounts.Add(account);
}
public void Deposit()
{
int accountId;
Console.Write("Enter your account number: ");
int.TryParse(Console.ReadLine(), out accountId);
var account = Accounts.FirstOrDefault(a => a.Id == accountId);
if (account != null)
{
double amount;
Console.Write("Enter amount to deposit: ");
double.TryParse(Console.ReadLine(), out amount);
account.Balance += amount;
Console.Write("Your new balance is {0}", account.Balance);
}
else
{
Console.WriteLine("That account does not exist!");
}
}
}
I have a parent class which is essentially a glorified list. It's extended by several subclasses for various functionalities.
public class HierarchialItemList<ItemType> : IEnumerable<ItemType>
{
public ItemType this[String itemCode]
{
get
{
foreach (IHierarchialItem curItem in hierarchialItems)
{
if (curItem.Code.Equals(itemCode, StringComparison.CurrentCultureIgnoreCase))
{
return ((ItemType)curItem);
}
}
return (default(ItemType));
}
}
public ItemType this[Int32 index]
{
get
{
return (hierarchialItems[index]);
}
}
}
public class DatabaseList : HierarchialItemList<Database>
{
public DatabaseList this[CommonDatabaseType typeToFilter]
{
get
{
DatabaseList returnList = new DatabaseList();
foreach(Database curDatabase in this)
{
if (curDatabase.DatabaseType.Equals(typeToFilter))
{
returnList.Add(curDatabase);
}
}
return (returnList);
}
}
public DatabaseList this[Environments.RMSEnvironment environmentToFilter]
{
get
{
DatabaseList returnList = new DatabaseList();
foreach(Database curDatabase in this)
{
if (curDatabase.ParentEnvironment.Equals(environmentToFilter))
{
returnList.Add(curDatabase);
}
}
return (returnList);
}
}
}
The problem is that C# thinks that this:
Database testDatabase = sampleDatabaseList[0];
Is an error and that the indexer should be returning a DatabaseList, not a Database. You and I both know that's false. Any workarounds or do all indexers have to have the same return type?
Edit: I just figured out that it's because of using an enumeration as an indexer which is internally an integer. Still, any way to use both an enumeration and an integer?
Edit 2: As requested, here is some compiliable test code which demonstrates the problem.
using System;
using System.Collections.Generic;
namespace CSQT
{
class A<T>
{
List<T> temp;
public A()
{
temp = new List<T>();
}
public void AddItem(T itemToAdd)
{
temp.Add(itemToAdd);
}
public T this[String code]
{
get { return (temp[0]); }
}
public T this[Int32 index]
{
get { return (temp[index]); }
}
}
class B : A<String>
{
public B()
: base()
{
}
public B this[BTypes testType]
{
get
{
return (this);
}
}
}
enum BTypes { TEMP1, TEMP2 };
class C
{
public C()
{
B temp = new B();
//Compile error: Cannot implicitly convert type 'CSQT.B' to 'string'
String temp2 = temp[0];
//Compile error: Cannot convert type 'CSQT.B' to 'string'
String temp3 = (String)temp[0];
//This compiles and runs but instead of going to A.this[int32], it goes to B.this[BTypes testType]
B temp4 = temp[0];
}
}
}
Why do we know that to be false? The line
Database testDatabase = sampleDatabaseList[0];
invokes the indexer with the parameter 0 which is a int literal and therefore, seeing that DatabaseList inherits from HierarchialItemList<Database> will invoke the indexer defined by
public ItemType this[Int32 itemCode] { get; }
which is declared to return an ItemType. You haven't told us what ItemType is. We have no reason to know that an ItemType can be assigned to a variable of type Database.
Indexers do not have to return the same type. However, it is not possible to overload solely on the basis of return type. That is, this is legal
class IndexerTest {
public int this[int index] {
get {
return 0;
}
}
public string this[double index] {
get {
return "Hello, success!";
}
}
}
This is not
class IndexerTest {
public int this[int index] {
get {
return 0;
}
}
public string this[int index] {
get {
return "Hello, fail!";
}
}
}
Responding to your edit:
Edit: I just figured out that it's because of using an enumeration as an indexer which is internally an integer. Still, any way to use both an enumeration and an integer?
If you want to invoke the indexer that accepts an enum, invoke it like so:
sampleDatabaseList[Environments.RMSEnvironment.SomeEnumValue];
This is perfectly valid code.
class SomeClass { }
public class A<T> : IEnumerable<T>
{
public T this[int index]
{
get
{
return (this[index]);
}
}
public T this[String index]
{
get
{
return (this[index]);
}
}
}
public class B : A<SomeClass>
{
public B this[char typeToFilter]
{
get
{
return new B();
}
}
}
B classList = new B();
SomeClass test = classList[0];
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TestNameSpace
{
public class Employee : Person
{
string id;
public string Id
{
get { return id; }
set { id = value; }
}
decimal salary;
public decimal Salary
{
get { return salary; }
set { salary = value; }
}
string password;
public string Password
{
set { password = value; }
}
int ichk = 1, schk = 1, pchk = 1;
public Employee()
: base()
{
Id = null;
Salary = Convert.ToDecimal("0.0");
Password = null;
}
public Employee(string n, char g, DateTime d, string empid, decimal sal, string pwd)
: base(n, g, d)
{
Id = empid;
Salary = sal;
Password = pwd;
}
public override void Accept()
{
base.Accept();
try
{
Console.Write("Enter the EMPID:");
Id = Console.ReadLine();
if (string.IsNullOrEmpty(Id) == true)
{
ichk = 0;
Console.WriteLine("No ID entered!");
}
string salcheck;
Console.Write("Enter the Salary:");
salcheck = Console.ReadLine();
if (string.IsNullOrEmpty(salcheck) == true)
{
schk = 0;
Console.WriteLine("Invalid Salary");
}
else
{
Salary = Convert.ToDecimal(salcheck);
if (Salary < 0)
{
schk = 0;
Console.WriteLine("Invalid Salary");
}
}
Console.Write("Enter Password:");
Password = Console.ReadLine();
if (string.IsNullOrEmpty(password) == true)
{
pchk = 0;
Console.WriteLine("Empty Password!");
}
else
{
string pwd;
int pchk = 0;
do
{
Console.Write("Re-Enter Password:");
pwd = Console.ReadLine();
if (string.IsNullOrEmpty(pwd) == true || pwd != password)
Console.WriteLine("Passwords don't match!");
else
pchk = 1;
} while (pchk == 0);
}
}
catch (Exception e)
{
Console.Write(e.Message);
}
}
public override void Print()
{
base.Print();
if (ichk == 1)
{
Console.WriteLine("EMPID:{0}", Id);
}
else
Console.WriteLine("No Id!");
if (schk == 1)
{
Console.WriteLine("Salary:{0}", Salary);
}
else
Console.WriteLine("Invalid Salary!");
}
}
}
------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TestNameSpace
{
public class Person
{
protected string name;
public string Name
{
get { return name; }
set { name = value; }
}
protected char gender;
public char Gender
{
get { return gender; }
set { gender = value; }
}
protected DateTime? dob;
public DateTime? Dob
{
get { return dob; }
set { dob = value; }
}
protected int age;
public int Age
{
get { return age; }
}
public Person()
{
Name = "Default";
Gender = 'M';
Dob = null;
age = 0;
}
public Person(string n, char g, DateTime d)
{
Name = n;
Gender = g;
Dob = d;
age = DateTime.Now.Year - Dob.Value.Year;
}
int nchk = 1, gchk = 0, dchk = 0;
string datetimecheck, gendercheck;
public virtual void Accept()
{
try
{
Console.Write("Enter the name:");
Name = Console.ReadLine();
if (string.IsNullOrEmpty(Name)==true)
{
nchk = 0;
Console.WriteLine("No name entered!");
}
Console.Write("Enter the Date of birth:");
datetimecheck = Console.ReadLine();
if (string.IsNullOrEmpty(datetimecheck) == true)
{
dchk = 0;
Console.WriteLine("No date entered!");
}
else
{
Dob = Convert.ToDateTime(datetimecheck);
age = DateTime.Now.Year - Dob.Value.Year;
dchk = 1;
}
Console.Write("Enter Gender:");
gendercheck = Console.ReadLine();
if (gendercheck != "m" && gendercheck != "M" && gendercheck != "f" && gendercheck != "F")
{
gchk = 0;
Console.WriteLine("Invalid Gender");
}
else
{
gchk = 1;
Gender = Convert.ToChar(gendercheck);
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
public virtual void Print()
{
Console.WriteLine("\n\nThe Employee Details are:\n");
if (nchk == 1)
{
Console.WriteLine("Name:{0}", Name);
}
else
Console.WriteLine("No Name!");
if (gchk == 1)
{
Console.WriteLine("Gender:{0}", Gender);
}
else
Console.WriteLine("No Gender!");
if (dchk == 1)
{
Console.WriteLine("Date Of Birth:{0}", Dob);
Console.WriteLine("Age:{0}", Age);
}
else
Console.WriteLine("No Date Of Birth!");
}
}
}
After adding the necessary classes and attributes to get your code sample to compile, I was able to run this statement with no issues:
Database testDatabase = sampleDatabaseList[0];
If you're getting an error that sampleDatabaseList[0] returns a DatabaseList, please provide a compilable code sample that contains the statement DatabaseList testDatabase = sampleDatabaseList[0];
---TRIGGER--
CREATE TRIGGER TriggerTest
ON EMP
AFTER INSERT, UPDATE, DELETE
AS
BEGIN
declare #day varchar(10)
select #day=datename(dw,getdate())
declare #hour int
Select #hour=convert(varchar(2),getdate(),114)
if ( #hour < 9 OR #hour > 13 OR #day = 'Saturday' OR #day = 'Sunday')
BEGIN
if UPDATE(EMPID)
RAISERROR ('Error!',1,16)
rollback tran
END
END
Insert into EMP values(1003,'A','A')
drop trigger TriggerTest
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TestNameSpace
{
public class Employee:Person
{
string id;
public string Id
{
get { return id; }
set { id = value; }
}
decimal salary;
public decimal Salary
{
get { return salary; }
set { salary = value; }
}
string password;
public string Password
{
set { password = value; }
}
int ichk = 1, schk = 1, pchk = 1;
public Employee()
: base()
{
Id = null;
Salary = Convert.ToDecimal("0.0");
Password = null;
}
public Employee(string n, char g, DateTime d, string empid, decimal sal, string pwd)
: base(n, g, d)
{
Id = empid;
Salary = sal;
Password = pwd;
}
public override void Accept()
{
base.Accept();
try
{
Console.Write("Enter the EMPID:");
Id = Console.ReadLine();
if (Id == null)
{
ichk = 0;
Console.WriteLine("No ID entered!");
}
Console.Write("Enter the Salary:");
Salary = Convert.ToDecimal(Console.ReadLine());
if (Salary < 0)
{
schk = 0;
Console.WriteLine("Invalid Salary");
}
Console.Write("Enter Password:");
Password = Convert.ToString(Console.ReadLine());
if (password == null)
{
pchk = 0;
Console.WriteLine("Empty Password!");
}
}
catch (Exception e)
{
Console.Write(e.Message);
}
}
public override void Print()
{
base.Print();
if (ichk == 1)
{
Console.WriteLine("EMPID:{0}", Id);
}
else
Console.WriteLine("No Id!");
if (schk == 1)
{
Console.WriteLine("Salary:{0}", Salary);
}
else
Console.WriteLine("Invalid Salary!");
}
}
}
-----PERSON-----
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TestNameSpace
{
public class Person
{
protected string name;
public string Name
{
get { return name; }
set { name = value; }
}
protected char gender;
public char Gender
{
get { return gender; }
set { gender = value; }
}
protected DateTime dob;
public DateTime Dob
{
get { return dob; }
set { dob = value; }
}
protected int age;
public int Age
{
get { return age; }
}
public Person()
{
Name = "Default";
Gender = 'M';
Dob = Convert.ToDateTime("09 / 12 / 1990");
age = 0;
}
public Person(string n, char g, DateTime d)
{
Name = n;
Gender = g;
Dob = d;
age = DateTime.Now.Year - Dob.Year;
}
int nchk = 1, gchk = 1, dchk = 1;
public virtual void Accept()
{
try
{
Console.Write("Enter the name:");
Name = Console.ReadLine();
if(Name == null)
{
nchk = 0;
Console.WriteLine("No name entered!");
}
Console.Write("Enter the Date of birth:");
Dob = Convert.ToDateTime(Console.ReadLine());
if (Dob == null)
{
dchk = 0;
Console.WriteLine("No date entered!");
}
else
{
age = DateTime.Now.Year - Dob.Year;
}
Console.Write("Enter Gender:");
Gender = Convert.ToChar(Console.ReadLine());
if (Gender != 'm' && Gender != 'M' && Gender != 'F' && Gender != 'f')
{
gchk = 0;
Console.WriteLine("Invalid Gender");
}
}
catch (Exception e)
{
Console.Write(e.Message);
}
}
public virtual void Print()
{
Console.WriteLine("\n\nThe Employee Details are:\n");
if (nchk == 1)
{
Console.WriteLine("Name:{0}", Name);
}
else
Console.WriteLine("No Name!");
if (gchk == 1)
{
Console.WriteLine("Gender:{0}", Gender);
}
else
Console.WriteLine("No Gender!");
if (dchk == 1)
{
Console.WriteLine("Date Of Birth:{0}", Dob);
Console.WriteLine("Age:{0}", Age);
}
else
Console.WriteLine("No Date Of Birth!");
}
}
}