Method that prints text contained in a tsv file to console - c#

I am trying to print two methods that i have created but i cant figure out how to do it.
My project consists of Language.cs file in addition to Program.cs
This method in Language.cs:
public static void PrettyPrintAll(IEnumerable<Language> langs)
{
foreach (var printsAll in langs)
{
Console.WriteLine(printsAll.Prettify());
}
}
Prints out this method that is also in Language.cs:
public string Prettify()
{
return $"{Year}, {Name}, {ChiefDeveloper}, {Predecessors}";
}
this method prints out every query result (is also in Language.cs):
public static void PrintAll(IEnumerable<Object> sequence)
{
foreach (var prints in sequence)
{
Console.WriteLine(prints);
}
}
Language class code other than the methods above:
namespace ProgrammingLanguages
{
public class Language
{
public static Language FromTsv(string tsvLine)
{
string[] values = tsvLine.Split('\t');
Language lang = new Language(
Convert.ToInt32(values[0]),
Convert.ToString(values[1]),
Convert.ToString(values[2]),
Convert.ToString(values[3]));
return lang;
}
public int Year
{ get; set; }
public string Name
{ get; set; }
public string ChiefDeveloper
{ get; set; }
public string Predecessors
{ get; set; }
public Language(int year, string name, string chiefDeveloper, string predecessors)
{
Year = year;
Name = name;
ChiefDeveloper = chiefDeveloper;
Predecessors = predecessors;
}
All the methods are within the Language.cs file.
My issue is that i do not understand how to print them, i have tried in many ways but always get an error code The name 'PrintAll' does not exist in the current context or something like that.
In main this is how i have tried to call the method PrintAll:
var stringLanguage = languages.Select(languagePrint => $"{languagePrint.Year}
{languagePrint.Name} {languagePrint.ChiefDeveloper}");
PrintAll(stringLanguage);

The static method PrintAll() belongs to the class Language and calling it from another class requier to prepend the class name first, such as Language.PrintAll()
public static void Main()
{
// some code ...
var stringLanguage = languages.Select(languagePrint => $"{languagePrint.Year} {languagePrint.Name} {languagePrint.ChiefDeveloper}");
// PrintAll(stringLanguage); <-- This won't work because there is no method PrintAll() in the current class
// This now refers to the correct class where the method belongs
Language.PrintAll(stringLanguage);
}
Another way to do that would be to include the static part of the class Language in the class where Main is (I assume the class Program) :
// replace namespace by the correct namespace of the class
using static namespace.Language;
class Program
{
public static void Main()
{
// some code ...
var stringLanguage = languages.Select(languagePrint => $"{languagePrint.Year} {languagePrint.Name} {languagePrint.ChiefDeveloper}");
// This now works because the static parts were imported
PrintAll(stringLanguage);
}
}
However, I discourage using this, because this may lead to confusion

Related

Set returned value from method as public string in C#

I need to get string from one class to another class,
It is possible to set public string from method I mean like in this code:
class test
{
static void Main(string[] args)
{
load();
}
public class Data
{
public string datacollected { get; set; }
}
public static void load()
{
string fileName = "samplefile.json";
string jsonString = File.ReadAllText(fileName);
Data datacfg = new Data();
var datanew = System.Text.Json.JsonSerializer.Deserialize<List<Data>>(jsonString);
datacfg = datanew.First();
}
public string datacollected = datacfg.datacollected;
}
i want to use string datacollected in another class and in another public void
The datacollected member that is directly in the test class is not a property. It's a field. Fields that have an assignment on the same statement as the declaration are evaluated before* the class's constructor (ie: before the Main method runs).
You probably want it to be a property instead, which is evaluated each time you access the member. The simplest method to fix that is by adding a > after the equals.
public string datacollected => datacfg.datacollected;
You've got two other problems though.
datacollected (in the test class) isn't static. All of your methods are static, and therefor wouldn't be able to access the non-static member.
You've still got the problem where the datacfg is a local variable that is defined inside the load method. You can't use variables outside their defined scope.
Option 1: you only need the parsed file data in the method that called load.
Change load to return the parsed data, rather than save it to a class-global variable.
using System.Text.Json;
static class test
{
static void Main(string[] args)
{
Data loadedData = load();
}
public static Data load()
{
string fileName = "samplefile.json";
string jsonString = File.ReadAllText(fileName);
return JsonSerializer.Deserialize<List<Data>>(jsonString).First();
}
}
public class Data
{
public string datacollected { get; set; }
}
Option 2: If you really need some global variable, put the whole Data object up to a field instead. This doesn't use a property - there's really no advantage in this case.
using System.Text.Json;
static class test
{
// assuming you're using nullable reference types (the "?")
private static Data? loadedData;
static void Main(string[] args)
{
load();
Console.WriteLine(loadedData!.datacollected);
// "!" to tell compiler that you know loadedData
// shouldn't be null when executed
}
public static void load()
{
string fileName = "samplefile.json";
string jsonString = File.ReadAllText(fileName);
loadedData = JsonSerializer.Deserialize<List<Data>>(jsonString).First();
}
}
public class Data
{
public string datacollected { get; set; }
}
I'd go with Option 1 if at all possible.
* I don't remember if it's before, during, or after.
You can declare a class like this
public class UseData
{
private List<Data> _data=null;
public string datacollected
{
get
{
if (_data == null)
LoadData();
return _data.First().datacollected;
}
}
private void LoadData()
{
string fileName = "samplefile.json";
string jsonString = File.ReadAllText(fileName);
_data = System.Text.Json.JsonSerializer.Deserialize<List<Data>>(jsonString);
}
}
which have a private list of data and it loads from your json file at first time you called. Next time you call it, as the private _data object is filled, it wont load again and the datacollected property returns the first data object's datacollected string property.

C# classes not printing out

I’m trying to create a program which has multiple classes. In the program.cs I have inserted example text but whenever I run the program it doesn’t output the text it only outputs the name of the program and the class files, e.g. Testprogram.Customer
And I can’t workout why.
The Bank code is:
namespace CashMachine
{
class Bank
{
private string bankname;
private string location;
public Bank(string name, string location)
{
this.bankname = bankname;
this.location = location;
}
public string Getname()
{
return this.bankname;
}
public string Getlocation()
{
return this.location;
}
}
}
The program cs code is:
namespace CashMachine
{
class Program
{
static void Main(string[] args)
{
Bank b = new Bank("NatWest", "London");
{
Console.WriteLine(b);
}
Console.WriteLine();
Console.WriteLine();
Customer c = new Customer("Joe", "UK", "joelndn", "May");
Console.WriteLine(c);
Console.ReadKey();
}
}
}
If we take the first example, of Bank, you have:
Bank b = new Bank("NatWest", "London");
Console.WriteLine(b);
Now; the system doesn't automatically know what you want to write about the Bank, but everything that subclasses object has a public virtual string ToString() method, for creating a text representation of a type, so: this is what gets called. The default implementation of ToString() is to output the type name, but if you want to do something more interesting: tell it what you want.
I would suggest:
public override string ToString()
{
return Getname();
}
You can do something similar with Customer to tell it what the default output would be for that.
Alternatively: just be explicit in your output code, i.e.
Console.WriteLine(b.Getname());
Finally, you might want to consider properties instead of methods like Getname, for example (using modern C# syntax):
class Bank
{
public string Name { get; }
public string Location { get; }
public Bank(string name, string location)
{
Name = name;
Location = location;
}
public override string ToString() => Name;
}

Error on static Class

public class Program
{
public static void Main(string[] args)
{
var c = check.myValue("Example 1"); //This is the pattern I've to use, don't want to create an object (Is it possible to use it with static class)
Console.WriteLine(c.result1);
Console.WriteLine(c.result2);
}
}
public static class check
{
public static void myValue(string qr)
{
public string result1 = "My Name" + qr;
public string result1 = "You're" + qr;
}
}
See here Online Example (Code is not working)
Every thing on main function I've to use exactly the same pattern because I'll use it in a lot of different classes and I don't want to create object each and every time by using non-static class.
Please correct me if I'm wrong
There's a lot wrong with the syntax of that code, which #Sergey addresses in his answer.
You appear to want to return an instance of a class from a static method, and that class should contain two properties.
You can do that by creating the actual, nonstatic class containing the properties:
public class Check
{
public string Result1 { get; set; }
public string Result2 { get; set; }
}
Then return a new instance from the static method therein:
public static Check MyValue(string qr)
{
var result = new Check();
result.Result1 = "My Name" + qr;
result.Result2 = "You're" + qr;
return result;
}
However, you're saying in the comments in your code that you don't want to use an object.
In that case it appears you want to use static properties. That's generally not recommendable, but it would look like this:
public static class Check
{
public static string Result1 { get; set; }
public static string Result2 { get; set; }
public static void MyValue(string qr)
{
Result1 = "My Name" + qr;
Result2 = "You're" + qr;
}
}
Then you can read Check.Result1 after calling the method MyValue().
Your code is totally wrong
myValue method returns void. You cannot assign void return value to variable.
You cannot have public modifiers for local variables.
You cannot have local variables with same name in same scope
If you want to return two values from method, then you should return object with two fields - custom class or tuple. You can also use out parameters, but I don't think it's your case
public static class Check
{
public static Tuple<string, string> MyValue(string qr)
{
return Tuple.Create($"My Name {qr}", $"You're {qr}");
}
}
With C# 7 it's a little bit better. You can write this method in one line and provide names for tuple properties
(string MyName, string YourName) MyValue(string qr) => ($"My Name {qr}", $"You're {qr}");
Usage
var result = Check.MyValue("Example 1");
Console.WriteLine(result.Item1); // result.MyName
Console.WriteLine(result.Item2); // result.YourName
You can practice with creating custom class with nicely named properties instead of using tuples.

DLL Property no settable

Why Could I not set my Property?
The DLL is imported and all methods are reachable but the URL property wont show up and also seems to not exists
http://prntscr.com/6y2az8
Dll Code:
namespace Steap
{
public class SteapAPI
{
public static String URL
{
get;
set;
}
public static XmlReader r = XmlReader.Create("");
public int getSteamID64()
{
int ID = 0;
r.ReadToFollowing("steamID64");
ID = r.ReadContentAsInt();
return ID;
}
public string getSteamID()
{
string ID = String.Empty;
r.ReadToFollowing("steamID");
ID = r.ReadContentAsString();
return ID;
}
public string getName()
{
return getSteamID();
}
}
}
I also used string intead of String and I need the static for the later statement
In the image that you added you are trying to access it like this:
SteapAPI sapi = new SteapAPI);
sapi.URL = // ... do something
Your property is static, so you should call it from class and not from instance:
SteapAPI.URL = // ... do something
Static properties are on the class not the instance. Use
SteapAPI.URL
Keep in mind this means the value is shared by all instances of the class.
If it is static then you access it like
SteapAPI.URL

Common functions and helpers ASP.NET MVC

I don't get something, and if somebody can clarify:
I need to access this function / helper from here and there:
namespace Laf.Helpers
{
public class Common
{
public string TimeSpanToString(TimeSpan val)
{
return val.ToString(#"hh\:mm");
}
}
}
And in my controller I access it by:
var tmp = new Common();
string str = tmp.TimeSpanToString(tp.DepartureTime);
transferPoint.Add(
new ListTransferPointVM { PortName = tp.PortName, DepartureTime = str }
str);
And the question is how can I achieve and not have duplicate in every controller:
DepartureTime = TimeSpanToString(tp.DepartureTime)
Possible Answer
I just found a way that compiler is not frowning on:
public class TransferController : Controller
{
private Common common = new Common();
public ActionResult Index ()
{
...
and later, when I need it:
string time = common.TimeSpanToString((TimeSpan)variable);
You could make your method string TimeSpanToString(TimeSpan) a static method. This way you can access it without having to make a Common object. Your code will look as follows:
namespace Laf.Helpers
{
public class Common
{
public static string TimeSpanToString(TimeSpan val)
{
return val.ToString(#"hh\:mm");
}
}
}
And your Controller:
transferPoint.Add(
new ListTransferPointVM {
PortName = tp.PortName,
DepartureTime = Common.TimeSpanToString(tp.DepartureTime) }
Common.TimeSpanToString(tp.DepartureTime));
EDIT: As suggested by Michael Petrotta an extension method would be better. An implementation could be:
namespace LaF.ExtensionMethods
{
public static class MyExtensions
{
public static string TimeSpanToString(this TimeSpan ts)
{
return ts.ToString(#"hh\:mm");
}
}
}
You can now call the method like:
tp.DepartureTime.TimeSpanToString();
More on Extension Methods in C#

Categories

Resources