using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ex1
{
internal class Program
{
static void Main(string[] args)
{
createCity("ex", 1, "ex1");
Console.ReadKey();
}
public void createCity(string name, int showOrder, string objectName)
{
City myObj = new City(name, showOrder);
}
}
}
using System;
public class City
{
public City()
{
string name;
static int code = 1;
int showOrder;
City(string name, int showOrder)
{
this.name = name;
this.showOrder = showOrder;
this.code++;
}
}
}
Any idea why? new to C#.
It doesn't know why the class City is, I don't understand why. I created it in the same project with the add option.
I'm just trying to create a new object of the class in the main.
create a constructor like this:
public City()
{
}
or with parameters:
public City(string name, int showOrder)
{
...
}
define the properties or fields of your class outside of the constructor
public class City
{
private string name { get; set; }
private int code { get; set; } = 1;
private int showOrder { get; set; }
}
Your 'code' property / field should not be static. This is causing an error in your constructor
int code = 1;
the reason you can't do createCity() inside the main method is because it is marked as static. Removing the static keyword should work.
private void Main(string[] args)
{
createCity("ex", 1, "ex1");
Console.ReadKey();
}
However you need a static void Main(string[] args) method in a console app, so I made createCity static as well
Full working example:
namespace ex1
{
public class Program
{
private static void Main(string[] args)
{
createCity("ex", 1, "ex1");
Console.ReadKey();
}
public static void createCity(string name, int showOrder, string objectName)
{
City myObj = new City(name, showOrder);
}
}
}
public class City
{
public City()
{
}
private string name { get; set; }
private int code { get; set; } = 1;
private int showOrder { get; set; }
public City(string name, int showOrder)
{
this.name = name;
this.showOrder = showOrder;
this.code++;
}
}
There are many things to fix:
static: Please make sure you understand this concept
This applies to:
static void createCity
code++;
The City class has multiple constructors and the class variable was defined in the wrong place.
You have to set the constructor public or at least internal:
public City(string name, int showOrder)
Corrected code:
Program.cs:
using System;
namespace ex1
{
internal class Program
{
static void Main(string[] args)
{
createCity("ex", 1, "ex1");
Console.ReadKey();
}
public static void createCity(string name, int showOrder, string objectName)
{
City myObj = new City(name, showOrder);
}
}
}
City.cs:
namespace ex1
{
public class City
{
string name;
static int code = 1;
int showOrder;
public City()
{
}
public City(string name, int showOrder)
{
this.name = name;
this.showOrder = showOrder;
code++;
}
}
}
Please try this following code :
using System;
namespace ex1
{
internal class Program
{
static void Main(string[] args)
{
City c = createCity("ex", 1, "ex1");
Console.WriteLine(c.ToString());
Console.ReadLine();
}
public static City createCity(string name, int showOrder, string objectName)
{
return new City(name, showOrder);
}
}
public class City
{
private string name;
private int code = 1;
private int showOrder;
public City(string name, int showOrder)
{
this.name = name;
this.showOrder = showOrder;
this.code++;
}
public override string ToString() => $"name: {name}; code:{code}; showOrder: {showOrder}";
}
}
Related
I have a class
public class MyCoolProp
{
public string FullName {get;set;}
}
and in another Class i have this as Property:
public class MyMainClass
{
public MyCoolProp coolprop {get;set;}
public void DoSomething()
{
MessageBox.Show(nameof(coolprop.FullName));
}
}
The Actual Result is: "Fullname"
But i want a combination like this: "coolprop.FullName"
i dont want to do something like this:
nameof(coolprop) + "." + nameof(coolprop.FullName);
Maybe its possible in an extension?
If i rename the Property "coolprop" the output should also have the new name
Depending on exactly what you want to do, you might be able to use CallerArgumentExpressionAttribute. That does mean you need to be willing to actually evaluate the property as well, even if you don't use it.
Note that this requires a C# 10 compiler.
Here's a complete example:
using System.Runtime.CompilerServices;
public class MyCoolProp
{
public string FullName { get; set; }
}
class Program
{
static MyCoolProp CoolProp { get; set; }
static void Main()
{
CoolProp = new MyCoolProp { FullName = "Test" };
WriteTextAndExpression(CoolProp.FullName);
}
static void WriteTextAndExpression(string text,
[CallerArgumentExpression("text")] string expression = null)
{
Console.WriteLine($"{expression} = {text}");
}
}
Output: CoolProp.FullName = Test
Source:
get name of a variable or parameter (modified a bit adjusted with your case)
You can use what System.Linq.Expression provides
code example:
using System.Linq.Expression
class Program
{
public static MyCoolProp coolProp { get; set; }
static void Main(string[] args)
{
coolProp = new MyCoolProp() { FullName = "John" };
DoSomething();
}
public static string GetMemberName<T>(Expression<Func<T>> memberExpression)
{
MemberExpression expressionBody = (MemberExpression)memberExpression.Body;
return expressionBody.ToString();
}
public static void DoSomething()
{
string prop = GetMemberName(() => coolProp.FullName);
Console.WriteLine(prop);
}
}
public class MyCoolProp
{
public string FullName { get; set; }
}
the GetMemberName method will return the namespace, class name, object name, and variable name (depends where the method is being called)
Output: Program.coolProp.FullName
So I'm working on a library management system and I'm new to C# so you may see me here a lot, the issue I'm currently having revolves around this. I'm trying to make it search in my list for the author and it succeeds in doing that, I just don't know how to make it print out the result to make it appear on the console as it currently just prints "Author exists!".
public static void LetaEfterBok()
{
Console.Write("Enter an author to search for a book: ");
string search = Console.ReadLine();
foreach (Bok b in newBok)
{
Bok Bok = new Bok();
if (b.namn.Equals(search))
Console.Write("Author " + Bok.Författare + " exists!");
}
}
If needed, here is the lists and variables
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace Bibliotek
{
//Definerar klassen Bok
class Bok
{
public string ID
{ get; set; }
public int tempID;
public string Författare
{ get; set; }
public string namn
{ get; set; }
public int BokCount;
public int x;
}
class Program
{
static List<Bok> newBok = new List<Bok>();
static List<BorrowDetails> borrowList = new List<BorrowDetails>();
static Bok Bok = new Bok();
static BorrowDetails borrow = new BorrowDetails();
//Menyn och startsidan till programmet
static void Main(string[] args)
{
StreamReader readFile = new StreamReader("bokfil.txt");
string s;
while((s = readFile.ReadLine()) != null)
{
Bok Bok = new Bok();
string[] BokData = s.Split(',');
Bok.namn = BokData[0];
Bok.Författare = BokData[1];
Bok.ID = BokData[2];
Bok.tempID = int.Parse(Bok.ID);
newBok.Add(Bok);
}
readFile.Close();
try if this method works for you...
public void LetaEfterBok()
{
Console.Write("Enter an author to search for a book: ");
string search = Console.ReadLine();
var book = newBok.FirstOrDefault(b => { return b.namn.Equals(search, StringComparison.OrdinalIgnoreCase); } );
if(book != null)
{
Console.WriteLine("Author " + book.Författare + " exists!");
}
}
I suggest you do the OOP thing and give your class Bok some functionality to display information about itself. You should override the ToString() method such that anytime you do WriteLine(b) where b is a Bok it would print a string with information of the book.
For example:
//Definerar klassen Bok
class Bok
{
public string ID
{ get; set; }
public int tempID;
public string Författare
{ get; set; }
public string namn
{ get; set; }
public int BokCount;
public int x;
public override string ToString()
{
return $"Title:{Författare}, Author:{namn}, ID:{ID} ({BokCount} Count)";
}
}
which can be used in the search as
public static void LetaEfterBok()
{
Console.Write("Enter an author to search for a book: ");
string search = Console.ReadLine();
foreach (Bok b in newBok)
{
if (b.namn.Equals(search))
{
Console.Write($"{b} Exists!");
}
}
}
To add more flexibility, also add a function in the Bok class that tries to match the author, and use the List<T>.Find() method to search the list
//Definerar klassen Bok
public class Bok
{
public string ID { get; set; }
public int tempID;
public string Författare { get; set; }
public string namn { get; set; }
public int BokCount;
public int x;
public override string ToString()
{
return $"Author:{Författare}, Name:{namn}, ID:{ID} ({BokCount} Count)";
}
public bool MatchAuthor(string name) => namn.ToUpper().StartsWith(name.ToUpper());
}
public static void LetaEfterBok()
{
Console.Write("Enter an author to search for a book: ");
string search = Console.ReadLine();
Bok match = newBok.Find((b) => b.MatchAuthor(search));
if (match!=null)
{
Console.Write($"{b} Exists!");
}
}
may I ask (as a novice) how do I call a method of a namespace, from another? Thank you for setting up an example if possible..
For example: (1) how do I set the properties of the MY_PRIMARY class to use them and (2) how do I call the AddNumbers method while in the MY_SECONDARY namespace? Thank you..
using.. etc
namespace MY_PRIMARY
{
public partial class SomethingHere
{
public Boolean holiday { get; set; } = false;
public int age { get; set; } = 18;
//etc...
}
class Program
{
private static void Main()
{
// some code here.. and..
public int AddNumbers(int number1, int number2)
{
int result = number1 + number2;
return result;
}
}
};
namespace MY_SECONDARY
{
public partial class SomethingElseHere
{
public Boolean holiday { get; set; } = false;
public int age { get; set; } = 18;
//etc...
}
class Program
{
static void Main()
{
// some code here..
}
// and..
Program outer = new Program();
outer.AddNumbers(3, 18); // <--- this is failing..
}
}
;
Namespaces are meant to group objects semantically. I'm kind of confused why you have 2 program classes. It would make more sense to have one class library, and one program. Anyway...
Suppose you have an Object1 in namespace Program.First,
And an Object2 in Program.Second
Object2 has a method named someMethod.
What you would do to call this method is
a) either add "using Program.Second", on you first class.
b) make an instance of Program.Second.Object2, and call the method on that.
https://www.programiz.com/csharp-programming/namespaces
So suppose you want to make an object of Program() do this:
using System;
namespace MY_PRIMARY
{
public partial class SomethingHere
{
public Boolean holiday { get; set; } = false;
public int age { get; set; } = 18;
//etc...
}
public class Program
{
public int AddNumbers(int number1, int number2)
{
int result = number1 + number2;
return result;
}
}
}
namespace MY_SECONDARY
{
public partial class SomethingElseHere
{
public Boolean holiday { get; set; } = false;
public int age { get; set; } = 18;
//etc...
}
class Program
{
static void Main()
{
MY_PRIMARY.Program outer = new MY_PRIMARY.Program();
outer.AddNumbers(3, 18);
}
}
}
(EDIT) updated my answer, i copied your code and saw that your namespaces were not closed off, therefor, you had nested namespaces, and classes in there. plus, some of the code was directly in your class instead of in a function.
Also, don't define 2 Main() methods, that's the entrypoint of the application.
...A little modification in POSITIONS of functions and classes... please, see:
using Alias = MY_PRIMARY.Program;
namespace MY_PRIMARY
{
public partial class SomethingHere
{
public Boolean holiday { get; set; } = false;
public int age { get; set; } = 18;
//etc...
}
public class Program
{
private static void Main()
{
// some code here.. and..
}
public int AddNumbers(int number1, int number2)
{
int result = number1 + number2;
return result;
}
};
namespace MY_SECONDARY
{
public partial class SomethingElseHere
{
public Boolean holiday { get; set; } = false;
public int age { get; set; } = 18;
//etc...
}
class Program
{
static void Main()
{
// some code here..
// and..
Alias outer = new Alias();
outer.AddNumbers(3, 18); // <--- OKAY...
}
}
}
}
See more:
Using namespaces (C# Programming Guide)
I have the following code:
public class UnitManager
{
public string Name { get; set; }
public string Firstname { get; set; }
public UnitManager(string name, string firstname)
{
this.Name = name;
this.Firstname = firstname;
}
}
class Other
{
}
class Program
{
static void Main(string[] args)
{
var player1 = new UnitManager("p1Name", "p1FirstName");
var player2 = new UnitManager("p2Name", "p2FirstName");
}
}
So, I have created 2 objects in the Program class.
what I'd like to do is access those instances from inside the Other class to // do stuff.
For example, access player name, put a title in his name, then assess player2 and put another title.
please, keep in mind, this is just an exemple, i'm not actually planning on using this, i'm just trying to grasp the concept.
I think you can write UnitManager a property in Other class, set the UnitManager
public class Other
{
public UnitManager manager1{ get; set; }
}
or write a method the pass UnitManager instance as parameter.
public class Other
{
public void SetTitle(UnitManager m1) {
// do your logic
}
}
Thank you all, i finally understood :)
Here's how i got it working with your help:
public class UnitManager
{
public string Name { get; set; }
public string Firstname { get; set; }
public UnitManager(string name, string firstname)
{
this.Name = name;
this.Firstname = firstname;
}
}
class Other
{
public static void AddTitle(UnitManager myUnit)
{
var titlePlusFullName = ("The Legendary" + " " + myUnit.Name + " " + myUnit.Firstname);
myUnit.Name = titlePlusFullName;
}
}
class Program
{
static void Main(string[] args)
{
var player1 = new UnitManager("john", "smith");
var player2 = new UnitManager("jen", "doe");
Other oT = new Other();
Other.AddTitle(player1);
Console.WriteLine("Player 1 name: " + player1.Name);
}
}
it displays full name + title.
I think you might want something like this:
public class UnitManager
{
public string Name { get; set; }
public string Firstname { get; set; }
public UnitManager(string name, string firstname)
{
this.Name = name;
this.Firstname = firstname;
}
}
public class Other
{
public void doSomething(UnitManager myUnit) {
//do something with each unit manager
}
}
public class Program
{
static void Main(string[] args)
{
//create an object of type UnitManager and place it into variable player1
var player1 = new UnitManager("p1Name", "p1FirstName");
//create an object of type UnitManager and place it into variable player2
var player2 = new UnitManager("p2Name", "p2FirstName");
//create an instance of the class Other
Other ot = new Other();
//call the method within the instantiated class ot (of type Other) and
//pass it the instance of the object UnitManager with a name
//of player1
result1 = ot.doSomething(player1);
result2 = ot.doSomething(player2);
}
}
If you have exactly 2 instances (players), why not create them within UnitManager?
// sealed: since we have 2 instances only we don't want to
// inherit (and create) derived classes
public sealed class UnitManager
{
public string Name { get; set; }
public string Firstname { get; set; }
// private: since we have 2 intances only we don't want to expose the constructor
private UnitManager(string name, string firstname)
{
this.Name = name;
this.Firstname = firstname;
}
// Think over renaming these fields: say, Player and Computer
public static readonly UnitManager Player1 = new UnitManager("p1Name", "p1FirstName");
public static readonly UnitManager Player2 = new UnitManager("p2Name", "p2FirstName");
}
Then address them as UnitManager.Player1 (UnitManager.Player2) e.g.
class Program
{
static void Main(string[] args)
{
UnitManager.Player1.Name = "First Name";
UnitManager.Player2.Name = "Second Name";
...
}
}
Or even (with a help of static import):
using static MyNamepace.UnitManager;
...
class Other
{
public void DoSomething()
{
// We don't have now put it as UnitManager.Player1
string name1 = Player1.Name;
...
}
}
Givin the following code:
internal interface IHasLegs
{
int NumberOfLegs { get; }
}
internal interface IHasName
{
string Name { get; set; }
}
class Person : IHasLegs, IHasName
{
public int NumberOfLegs => 2;
public string Name { get; set; }
public Person(string name)
{
Name = name;
}
}
class Program
{
static void ShowLegs(IHasLegs i)
{
Console.WriteLine($"Something has {i.NumberOfLegs} legs");
}
static void Main(string[] args)
{
Person p = new Person("Edith Piaf");
ShowLegs(p);
Console.ReadKey();
}
}
Is there a way of implementing ShowLegs so that it only accepts values that implement IHasLegs and IHasName, without having to declare a intermediate IHasLegsAndHasName: IHasLegs, IHasName ? Something like ShowLegs((IHasLegs, IHasName) i) {}.
static void ShowLegs<T>(T i) where T : IHasLegs, IHasName
{
Console.WriteLine($"{i.Name} has {i.NumberOfLegs} legs");
}