I am starting to learn c#, but i don’t know when to use new keyword, and when not to use it. generally i know why to use it, but as i am looking at some code on the internet, i can see that many times new keyword is not used – and those are places when i would use it.
example:
static void FileInfoClass()
{
//this usage of new keyword i understand.
FileInfo somefile = new FileInfo("c:\\test.txt");
if (!somefile.Exists)
{
//this is the place where i would like to use new
//like FileStream somefileStream = new FileStream();
FileStream somefileStream = somefile.Create();
somefileStream.Close();
somefile = new FileInfo("c:\\test.txt");
}
//same like before
StreamWriter texttoAdd;
texttoAdd = somefile.CreateText();
texttoAdd.WriteLine("This is a line in the file");
texttoAdd.Flush();
texttoAdd.Close();
}
this is the simplest example i can think of.
I understand your question this way: you know that
newcan be used to create an object, so you don’t understand why is it not used for every case where a new object “appears” in your code.Therefore, you want to know what is different in these two lines:
and
Well, the second one is not a direct construction of the object. Actually this command by itself does not create an object, it just calls a function that returns an object.
Given that the function is called “Create()”, we can guess this function will create an object and return it (or will call another function that create an object and return it). But this is only a convention. Nothing in the language says that function called “Create()” should really create objects.
So when you use this function, your code is not the one responsible to create the object and therefore you don’t use the keyword
new. This pattern is called a Factory method.