Can't throwaway result of a val1 && val2? - c#

I'm trying to do something like
public class Program
{
private static readonly Random r = new Random();
public static void Main()
{
RandomBool() && RandomBool();
}
private static bool RandomBool()
{
bool b = r.Next() % 2 == 0;
Console.WriteLine("Random bool value is {0}", b);
return b;
}
}
i.e. execute RandomBool() until it's false. (You can do this in JavaScript)
I guess I have to do
public static void Main()
{
bool throwAwayValue = RandomBool() && RandomBool();
}
Or is there a better way to do the same thing?

If you want to execute RandomBool repeatedly until it's false, can't you use while loop in your main?
while (RandomBool()) {
// wait
}
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/while

Related

Assigning to a variable by reference?

Thanks to the kind folks who answered my previous question from a few days ago, I now know how to pass arguments by reference:
static void Main()
{
int i = 0;
Add(ref i, 100);
// now i == 100
}
static void Add(ref int arg, int increment)
{
arg += increment;
}
But is there a way for me not to just pass i by reference, but actually store its location in another variable? By that I mean use i like I did in my example; affecting the original instance, but in a way that's permanently linked and not leaving scope.
I vaguely know that I could use a pointer to determine the location in unsafe context but I was wondering if I could do this without any of that, or if it is just recommended to use the unsafe method.
If you are using C# 7 you can use ref local and ref return to store an updateable reference to any field.
In this example I change the private field _privateField from 0 to 100 from outside Foo, the class in which it is defined, by returning it as a ref int and updating it by reference.
class Foo
{
private int _privateField = 0;
public ref int GetReference()
{
return ref _privateField;
}
public override string ToString()
{
return _privateField.ToString();
}
}
public class Program
{
public static void Main()
{
var foo = new Foo();
var referenceToPrivateField = foo.GetReference();
referenceToPrivateField = 100;
Console.WriteLine(foo);
}
}
Prior to that, you'd have to store the value in a field contained in an object, and pass around a reference to the object instead.
In this example I change the value from 0 to 100 from outside Foo, even though it is stored (indirectly) in a field that is private inside the Foo instance.
class ValueTypeReference<T> where T : struct
{
public T Value { get; set; }
}
class Foo
{
private ValueTypeReference<int> _privateField = new ValueTypeReference<int>{ Value = 0 };
public ValueTypeReference<int> GetReference()
{
return _privateField;
}
public override string ToString()
{
return _privateField.Value.ToString();
}
}
public class Program
{
public static void Main()
{
var foo = new Foo();
var referenceToPrivateField = foo.GetReference();
referenceToPrivateField.Value = 100;
Console.WriteLine(foo);
}
}
Output:
100
Well, if I udnerstood you correctly, you want the variable to have global scope, which can be achieved by putting variable as class field/property:
class Program
{
private static int _i;
static void Main()
{
_i = 0;
Add(100);
// now _i == 100
}
static void Add(int increment)
{
_i += 100;
}
}

Chaining constructors not updating variables as expected

I have created a class that looks similar to the one below. As you can see I created a few constructors that I am trying to chain using : this()
class RTTutils
{
#region Variables
private bool verbose = false;
private bool canWrite = false;
private int x;
private int y;
public RTTutils()
{
x = 5;
y = 5;
RTTCalc();
}
public RTTutils(int samples, bool verbose) : this()
{
this.verbose = verbose;
this.samples = samples;
}
public RTTutils(int samples, bool verbose, bool canWrite) : this()
{
this.verbose = verbose;
this.samples = samples;
this.canWrite = canWrite;
}
public RTTutils(int samples) : this(samples, false, false)
{
}
public RTTutils(bool verbose) : this()
{
this.verbose = verbose;
}
private void RTTCalc()
{
if (this.verbose)
Console.WriteLine("Test");
}
I am trying to initialize it using
RTTutils rttcalculator = new RTTutils(true);
or any other combination for verbose and canWrite, they still remain false though. As an example in this case we will see nothing printed in the console, even though I indicated true when initializing the class.
What am I doing wrong in this case?
You expect (wrongly) boolean class fields used in method RTTCalc to have values you set in constructors with parameters. However, the parameterless constructor executes before these assignments.
Do not call RTTCalc in parameterless constructor. Provide static factory methods instead:
class RTTutils
{
private bool verbose = false;
private bool canWrite = false;
private RTTutils()
{
sampleList.Add(100); // First sample should be 100
optionChosen.Add("E");
x = 5;
y = 5;
System.IO.File.Delete(this.path);
}
private RTTutils(bool verbose) : this()
{
this.verbose = verbose;
}
private void RTTCalc()
{
if (this.verbose)
Console.WriteLine("Test");
}
public static RTTutils Create(bool verbose)
{
RTTutils result = new RTTutils(verbose);
result.RTTCalc();
return result;
}
}
Given your code above, I rewrote it and it initializes verbose and canWrite as expected.
class Foo
{
private bool _verbose = false;
private bool _canWrite = false;
private int _samples;
private int x;
private int y;
public Foo(int samples, bool verbose, bool canWrite)
{
_verbose = verbose;
_canWrite = canWrite;
_samples = samples;
x = 5;
y = 5;
RTTCalc();
}
public Foo() : this(0, false, false) { }
public Foo(int samples) : this(samples, false, false) { }
public Foo(int samples, bool verbose) : this(samples, verbose, false) { }
private void RTTCalc()
{
Console.WriteLine($"V={_verbose}, S={_canWrite}");
Console.ReadKey();
}
}
class Program
{
static void Main(string[] args)
{
Foo test1 = new Foo(1, true, false);
Foo test2 = new Foo(1, true);
Foo test3 = new Foo();
}
}
Does this work for you? If not then you are doing something else that is not shown in your code that is affecting verbose and canWrite.

Override objects return value

I'm trying to compare an object with an int value such as
if (myObject - 5 == 0)
doSomething();
my class could look something like this: (most setters/getters removed, so don't mind that all variables are private)
public class SomeClass
{
public string name;
private int minValue;
private int maxValue;
private int currValue;
public int getCurrentValue()
{
return currValue;
}
}
What I'm trying to achieve is something like this:
someClassInstance - 5;
to be equal
someClassInstance.getCurrentValue() - 5;
Can I make an override for the object to act as an int (it's own variable) opposed to just being an object?
May be operator is the case?
public class SomeClass {
...
public static int operator -(SomeClass left, int right) {
if (Object.ReferenceEquals(null, left))
throw new ArgumentNullException("left");
return left.getCurrentValue() - right;
}
}
...
SomeClass someClassInstance = new SomeClass(...);
int result = someClassInstance - 5;
Another possibility (based on implicit operator) is to convert SomeClass implicitly to int whenever required:
public class SomeClass {
...
// Whenever int is requiered, but SomeClass exists make a conversion
public static implicit operator int(SomeClass value) {
if (Object.ReferenceEquals(null, value))
throw new ArgumentNullException("value");
return value.getCurrentValue();
}
}
...
SomeClass someClassInstance = new SomeClass(...);
int result = someClassInstance - 5;
Actually you would be much better off overriding operator int, that way you can do far more calculations with less overloads:
using System;
namespace Demo
{
public class SomeClass
{
public string name;
private int minValue;
private int maxValue;
public int currValue;
public int getCurrentValue()
{
return currValue;
}
public static implicit operator int(SomeClass value)
{
if (value == null)
throw new ArgumentNullException("value");
return value.currValue;
}
}
internal class Program
{
private void run()
{
var test = new SomeClass {currValue = 5};
if (test - 5 == 0)
Console.WriteLine("It worked");
if (test + 5 == 10)
Console.WriteLine("This also worked");
}
private static void Main()
{
new Program().run();
}
}
}
You could experiment with a mixture of implicit conversions and operator overloading, but from my experience you will never make it work as seamlessly as you wish (and as you could get it to work in C++).
If I were you, I would change the getCurrentValue to a property:
public int CurrentValue
{
get {return currValue};
}
and just use someClassInstance.CurrentValue -5

Call value from a method inside Main() function

I am trying to call a value from a method called GetInputstring from inside Main() method, and proceed to the next steps.
I am stuck regards to how I could get the value myInt and move along.
myInt (where it has two * around) inside Main() is where it gets the errors.
static void Main(string[] args)
{
GetInputstring(**myInt**);
if (**myInt** <= 0)
{
Write1(**myInt**);
}
else
{
Write2(**myInt**);
}
Console.ReadKey();
}
public int GetInputstring(int myInt)
{
string myInput;
//int myInt;
Console.Write("Please enter a number: ");
myInput = Console.ReadLine();
myInt = Int32.Parse(myInput);
return myInt;
}
static void Write1(int myInt)
{
while (myInt <= 0)
{
Console.WriteLine("{0}", myInt++);
}
}
static void Write2(int myInt)
{
while (myInt >= 0)
{
Console.WriteLine("{0}", myInt--);
}
}
MyInt is your parameter(the value you pass to your method) and it's not initialized. Further you don't catch your return value (which should be myInt)
You also need to make your methods static in order to call them from a static method or you create an instance of the class and invoke the method on it
That's how you'll get what you want:
static void Main(string[] args)
{
int myInt = GetInputstring(); //MyInt gets set with your return value
if (myInt <= 0)
{
Write1(myInt);
}
else
{
Write2(myInt);
}
Console.ReadKey();
}
public static int GetInputstring() //Deleted parameter because you don't need it.
{
string myInput;
//int myInt;
Console.Write("Please enter a number: ");
myInput = Console.ReadLine();
int myInt = Int32.Parse(myInput);
return myInt;
}
You need to initialize your myInt variable and store it in the local or global scope. With this variable you will need to set it with the value you get from GetInputString() because you are not passing the int as a ref it will not be assigned in the method. You also need to make your methods static so they can be called from Main without creating an instance, Ex: public static int GetInputstring()
int myInt = 0;
myInt = GetInputstring(myInt);
if (myInt <= 0)
{
Write1(myInt);
}
else
{
Write2(myInt);
}
Console.ReadKey();
Alternatively (And preferably), you could make GetInputString() assign the value because it dosen't need myInt to be passed as an parameter.
static void Main(string[] args)
{
int myInt = GetInputstring();
if (myInt <= 0)
{
Write1(myInt);
}
else
{
Write2(myInt);
}
Console.ReadKey();
}
public static int GetInputstring()
{
Console.Write("Please enter a number: ");
string myInput = Console.ReadLine();
return Int32.Parse(myInput);
}

How do you call a method from static main()?

I have a console application with a Main method and a function.
How can I make a function call from the Main method?
I know the code below won't work
static void Main(string[] args)
{
string btchid = GetCommandLine();// GetCommandline is a mthod which returns a string
}
There's also
var p = new Program();
string btchid = p.GetCommandLine();
Make the GetCommandLine static!
namespace Lab
{
public static class Program
{
static string GetCommandLine()
{
return "Hellow World!";
}
static void Main(string[] args)
{
System.Console.WriteLine(GetCommandLine());
System.Console.ReadKey();
}
}
}
You can change the function as a static and call it . Thats all.
static class Program
{
[STAThread]
static void Main()
{
string btchid = Program.GetCommandLine();
}
private static string GetCommandLine()
{
string s = "";
return s;
}
}
A linear search approach to your problem:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace LinearSearch
{
class Program
{
static void Main(string[] args)
{
int var1 = 50;
int[] arr;
arr = new int[10]{10,20,30,40,50,60,70,80,90,100};
int retval = linearsearch(arr,var1);
if (retval >= 1)
{
Console.WriteLine(retval);
Console.Read();
}
else
{ Console.WriteLine("Not found"); Console.Read(); }
}
static int linearsearch(int[] arr, int var1)
{
int pos = 0;
int posfound = 0;
foreach (var item in arr)
{
pos = pos + 1;
if (item == var1)
{
posfound = pos;
if (posfound >= 1)
break;
}
}
return posfound;
}
}
}
GetCommandLine must be a static function
string btchid = classnamehere.GetCommandLine();
Assuming that GetCommandLine is static
Something like this:
[STAThread]
static void Main(string[] args) {
string btchid = GetCommandLine();// GetCommandline is a mthod which returns a string
}
static string GetCommandLine(){
return "Some command line";
}

Categories

Resources