Error on static Class - c#

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.

Related

How to set up method variables to class object properties/values

Simply put how do you establish a connection between method variable decloration and connect it with class properties (or inner objects), lets say you have default or hard set values in a class like this (obviously they could be other types but for simplicity its set to strings) :
public class SampleClass
{
public string strA = "Something 1";
public string strB = "Something 2";
public string strC = "Something 3";
}
//think of it as a data layer where strings are pointers to dbSets
How do you leverage the same SampleClass in a method that allows ONLY pick of properties Method(property).
Easy sample that does what its supposed to:
public class ProccessClass
{
private string _dummyOut;
public ProccessClass Pick(string input)
{
this._dummyOut = input;
return this;
}
}
class Program
{
static void Main(string[] args)
{
var Test = new ProccessClass().Pick(new SampleClass().strB);
// we know this works and compiles and returns the strB
}
}
What would you have to convert to ommit the new instantiation and skip the class declaration (if possible but in theory should be doable)
new SampleClass().strB
needs to be just
strB
So how to get the final code to execute??
public class SampleClass
{
public string strA = "Something 1";
public string strB = "Something 2";
public string strC = "Something 3";
}
public class ProccessClass
{
private string _dummyOut;
public ProccessClass Pick(SampleClass sampleClass) //is it the variable declaration?
{
this._dummyOut = input;
return this;
}
}
class Program
{
static void Main(string[] args)
{
string Test = new ProccessClass().Pick(strB);
//so NO new keywords clean and easy set based on class provided above
}
}
Constructor and void setters but no go, the goal is to set the Hard relation ship between the method intake value and setters

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.

Method that prints text contained in a tsv file to console

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

c# initialize static variable from different classes

What I have is:
public static class IDs {
public static string someID { get; set; }
static IDs() {
log.info(someID);
// use someID here
}
}
public class otherClass {
public void otherMethod(string sym) {
IDs.someID = sym;
}
}
and then using an instance of otherClass like this:
otherClassInstance.otherMethod("someStringSymbol");
I dont have any build errors, but log.info(someID); is printing null.
I was expecting it to be someStringSymbol.
This is because the static constructor is called automatically before the first instance is created or any static members are referenced..
This means that when an instance of otherClass invokes IDs.someID = sym; the first operation that gets executed is the static constructor, i.e. the code inside static IDs().
At this point the static variable has not yet been initialized, and you are basically executing log.info(null);.
After the static constructor completes, the variable is initialized, so you should be able to see its value inside otherMethod, after the first reference of IDs.
Given the OP's requirement:
I want to use the value passed in someID in a switch statement
The solution could be to simply execute a static method whenever a new value is set, with the help of explicit getters and setters:
public static class IDs
{
private static string _someID; // backing field
public static string SomeID
{
get { return _someID; }
set
{
_someID = value;
DoSomethingWithSomeID();
}
}
private static DoSomethingWithSomeID()
{
// Use SomeID here.
switch (IDs.SomeID)
{
...
}
}
}
public class OtherClass
{
public void OtherMethod(string sym)
{
// This will set a new value to the property
// and invoke DoSomethingWithSomeID.
IDs.SomeID = sym;
}
}
DoSomethingWithSomeID will be invoked every time someone sets a new value to SomeID.
I dont think what you are trying to do is suited to static classes. I would try the following
public class IDs{
public string someID{ get; set; }
public IDs(string someId){
this.someID = someId;
log.info(this.someID);
//use someID here
}
}
pulic class otherClass{
public otherMethod(string sym){
IDs id = new IDs(sym);
}
}
public class anotherClass{
//access instance of otherClass in wrp and call otherMethod()
wrp.otherMethod("someStringSymbol")
}

Ref in async Task

How I can to pass a reference as a parameter to Async method in Windows Store App ? I'm looking for something like this:
var a = DoThis(ref obj.value);
public async Task DoThis(ref int value)
{
value = 10;
}
But error:
Async methods cannot have ref or out parameters
Has any another way?
Note:I need to pass exactly obj.value. This method would be used by different types of objects, by same type of objects, by one object, but I will pass obj.val_1, obj.val_2 or obj.val_10. All values will be same type (for ex string)
If you don't care about a little overhead and possibly prolonged lifetime of your objects, you could emulate the ref behavior by passing a setter and a getter method to the function, like this:
public async Task DoStuff(Func<int> getter, Action<int> setter)
{
var value1 = getter();
await DoSomeOtherAsyncStuff();
setter(value1 * value1);
}
And call it like this:
await DoStuff(() => obj.Value, x => obj.Value = x);
You could directly pass the object itself and set the value of the corresponding property inside the method:
var a = DoThis(obj);
public async Task DoThis(SomeObject o)
{
o.value = 10;
}
And if you do not have such object simply write one and have the async method take that object as parameter:
public class SomeObject
{
public int Value { get; set; }
}
You can always use the Task<> class and return the desired value. Then Your code would look something like:
var a = DoThis(obj.value);
obj.value = a.Result;
public async Task<int> DoThis(int value)
{
int result = value + 10; //compute the resulting value
return result;
}
EDIT
Ok, the other way to go with this that I can think of is encapsulating the update of the given object's member in a method and then passing an action invoking this method as the task's argument, like so:
var a = DoThis(() => ChangeValue(ref obj.value));
public void ChangeValue(ref int val)
{
val = 10;
}
public async Task DoThis(Action act)
{
var t = new Task(act);
t.Start();
await t;
}
As far as I tested it the change was made in the child thread, but still it's effect was visible in the parent thread. Hope this helps You.
You can't do this as you have it (as you know). So, a few work arounds:
You can do this by passing the initial object since it will be a reference type
var a = DoThis(obj);
public async Task DoThis(object obj) //replace the object with the actual object type
{
obj.value = 10;
}
EDIT
Based upon your comments, create an interface and have your classes implement it (providing it's always the same type you want to pass). Then you can pass the interface which is shared (maybe over kill, depends on your needs, or even unrealistic amount of work).
Or, provide a base class with the property! (I don't like this suggestion but since you're asking for something which can't be done it may suffice although I don't recommend it).
An example of the interface is here (not using what you have, but close enough using a Colsone App)
using System;
namespace InterfacesReferenceTypes
{
class Program
{
static void Main(string[] args)
{
MyClass mc = new MyClass();
DoThis(mc);
Console.WriteLine(mc.Number);
Console.ReadKey();
}
static void DoThis(IDemo id)
{
id.Number = 10;
}
}
class MyClass : IDemo
{
//other props and methods etc
public int Number { get; set; }
}
interface IDemo
{
int Number { get; set; }
}
}
EDIT2
After next comments, you will have to still use an interface, but re assign the value afterwards. I'm sure there is a better way to do this, but this works:
using System.Text;
namespace InterfacesRerefenceTypes
{
class Program
{
static void Main(string[] args)
{
MyClass mc = new MyClass();
Console.WriteLine(mc.Number);
mc.val1 = 3;
mc.val2 = 5;
mc.Number = mc.val2;
DoThis(mc);
mc.val2 = mc.Number;
Console.WriteLine(mc.val2);
Console.ReadKey();
}
static void DoThis(IDemo id)
{
id.Number = 15;
}
}
class MyClass : IDemo
{
public int val1 { get; set; }
public int val2 { get; set; }
public int Number { get; set; }
}
interface IDemo
{
int Number { get; set; }
}
}

Categories

Resources