metal_hard
New member
- Joined
- Nov 1, 2020
- Messages
- 4
- Programming Experience
- Beginner
hello guys, help me solve the error, I'm a beginner, so I don’t know how to solve it, I looked many times I can’t understand what is wrong
int n = 10;
int k = 10;
int[,] m = new int[n,k];
for (int i = 0; i<n; i++)
{
for (int j = 0; j<k; j++)
{
m[i,j] = i+j;
Console.WriteLine({0},m[i,j]);
}
}
_ = Console.ReadKey();
_ =
will discard or release the memory? I thought it was just to tell the compiler that you don't care about the return value. I didn't know that it will actually cause the return value to be automatically disposed or discarded. static void MethodA(string a, string b)
{
_ = string.Concat(a, b); /* Add var before _ and it no longer discard */
Debug.WriteLine(_); /* _ Does not exist. */
}
Because there is only a single discard variable, and that variable may not even be allocated storage, discards can reduce memory allocations.
use "_ =" to discard this result to release memory. like an dispose a object or null a same.
using System;
namespace SimpleCSConsole
{
class CodeMonkey : IDisposable
{
string _name;
bool disposedValue;
public CodeMonkey(string name) => _name = name;
protected virtual void Dispose(bool disposing)
{
if (!disposedValue)
{
Console.WriteLine($"I was disposed: {_name}");
if (disposing)
{
_name = null;
}
disposedValue = true;
}
}
~CodeMonkey()
{
// Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method
Dispose(disposing: false);
}
public void Dispose()
{
// Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method
Dispose(disposing: true);
GC.SuppressFinalize(this);
}
}
class Program
{
static void DoAction(string caption, Action action)
{
Console.WriteLine($">>> Starting {caption}");
action();
Console.WriteLine($"<<< Ending {caption}");
}
static void Main()
{
DoAction("Testing discard",
() => {
_ = new CodeMonkey("Monkey1");
});
DoAction("Testing setting to null",
() => {
var monkey = new CodeMonkey("Monkey2");
monkey = null;
});
DoAction("Testing explicit Dispose() call",
() => {
var monkey = new CodeMonkey("Monkey3");
monkey.Dispose();
monkey = null;
});
DoAction("Testing using keyword",
() => {
using (var monkey = new CodeMonkey("Monkey4"))
; // do nothing
});
Console.WriteLine("Done.");
}
}
}
>>> Starting Testing discard
<<< Ending Testing discard
>>> Starting Testing setting to null
<<< Ending Testing setting to null
>>> Starting Testing explicit Dispose() call
I was disposed: Monkey3
<<< Ending Testing explicit Dispose() call
>>> Starting Testing using keyword
I was disposed: Monkey4
<<< Ending Testing using keyword
Done.
I was disposed: Monkey2
I was disposed: Monkey1