Professional Documents
Culture Documents
Methods
A method is a code block that contains a series of statements. A program causes the
statements to be executed by calling the method and specifying any required
method arguments. In C#, every executed instruction is performed in the context of a
method.
The Main method is the entry point for every C# application and it's called by the
common language runtime (CLR) when the program is started.
Defining Methods in C#
When you define a method, you basically declare the elements of its structure. The
syntax for defining a method in C# is as follows –
Return type − A method may return a value. The return type is the data
type of the value the method returns. If the method is not returning any
values, then the return type is void.
using System;
namespace VOIDMETHODS
{
class Program
{
static void Main(string[] args)
{
writesomething();
writesomethingspecific("hello there method2 ");
Console.Read();
Console.WriteLine(s1);
}
}
}
METHOD WITH RETURN TYPE
using System;
namespace methodswithreturntype
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(ADD(3,4));
Console.WriteLine(DIV(25, 13));
Console.Read();
}
}
}
2. TRY CATCH AND FINALLY
using System;
namespace trycatchfinally
{
class Program
{
static void Main(string[] args)
{
string a = Console.ReadLine();
string b= Console.ReadLine();
try
{
int a1 = Int32.Parse(a);
int b1 = Int32.Parse(b);
Console.WriteLine(add(a1, b1));
}
catch (Exception)
{
Console.WriteLine("please eneter a number only");
}
finally
{
Console.WriteLine("this will execute anyways");
}
}
}
}
for example,
if you tried to start an Internet connection or if you try to write into a file, there
eventually can happen is error.
So let's say the Internet connection breaks or you don't have access to a file that you
want to write into or some other exceptions that can come up and you want to close
the connection or the file either way. So you have open to file and now you try to
write into that file and after you have written into that file within the try block and
maybe it worked, maybe it didn't work, but what you definitely want to do is to close
the file again, or you try to download something from the internet and if it worked or
it didn't work, doesn't matter. You need to close the connection to the Internet
afterwards, and that's something that you would do .