Inside Man
Inside Man

Reputation: 4372

Avoiding twice coding, One in if Condition and One in Assignment - C#

Here is my sample code:

if (_Timing != target.Split(':')[0] + ": ")
   _Timing = target.Split(':')[0] + ": ";

I check if _Timing is not equal to target.Split(':')[0] + ": " then I will assing it to _Timing. I execute this target.Split(':')[0] + ": " two times. I need to avoid it.

another example is this:

if (db.Students.FirstOrDefault(x => x.Name == "Joe") != null)
   var a = db.Students.FirstOrDefault(x => x.Name == "Joe");

here again, I execute db.Students.FirstOrDefault(x => x.Name == "Joe") two times. These samples are just some examples. I need to avoid twice coding like these.

I can do this due to answers received:

var splitted= target.Split(':')[0] + ": ";
if (_Timing != splitted)
   _Timing = splitted;

But I don't want to do something like this, because splitted will remain in memory. I'm looking for a way to not saving this temporary data into memory.

Is there any advice?

Upvotes: 0

Views: 225

Answers (3)

Rehan Shah
Rehan Shah

Reputation: 1627

According to your requirement you say that:

I can do this due to answers received:

var splitted= target.Split(':')[0] + ": ";
if (_Timing != splitted)
   _Timing = splitted;

But I don't want to do something like this, because splitted will remain in memory. I'm looking for a way to not saving this temporary data into memory. Is there any advice?

Yes There is one way to explicity remove variable from a memory.

You can try this to achieve that same thing and the variable splitted no longer remains in memory:

var splitted= target.Split(':')[0] + ": ";
if (_Timing != splitted)
{
   _Timing = splitted;
   splitted = null;
   GC.Collect(); // It this stage the 'splitted' is not longer remain in the memory.
}

Upvotes: 1

Ehsan Sajjad
Ehsan Sajjad

Reputation: 62488

You can hold the reusable statement in a variable and reuse wherever needed further down in your flow control:

var splitted= target.Split(':')[0] + ": ";
if (_Timing != splitted)
   _Timing = splitted;

the same goes for the linq queries :

var student = db.Students.FirstOrDefault(x => x.Name == "Joe");
if (student  != null)
{
  // do something here with student
}

if you want to avoid writing the linq query then you can introduce methods too:

public Student GetStudentByName(string name)
{
   return db.Students.FirstOrDefault(x => x.Name == "Joe");
}

and reuse it:

var student = GetStudentByName("Joe");
if (student  != null)
{
  // do something here with student
}

Upvotes: 4

Phillip Scott Givens
Phillip Scott Givens

Reputation: 5464

Remove the if block.

  _Timing = target.Split(':')[0] + ": ";

Move assignment out of the if block

var student = db.Students.FirstOrDefault(x => x.Name == "Joe");
if (student  != null)
{
  // 
}

Upvotes: 0

Related Questions