Out variables in C# 7.0

C# 7.0 brings some features to out variables. These new features help us write cleaner code and handle out variables better. This blog post provides samples of these new features in C# 7.0 and as a surprise it also demonstrates what compiler is doing with these new features.

Inline out variables

Let’s start with piece of code that demonstrates how TryParse() and some TrySomethingElse() methods work.

var intString = "1111";
int
i = 0;

if(int.TryParse(intString, out
i))
{
   
// it's integer
}
else
{
   
// it's not integer
}

The code above uses out variable i that needs to be declared before TryParse() method is called. In case of method with more out variables we have to declare all these variables before calling the method. Imagine three out variables of different type, by example.

C# 7.0 allows us define out variables inline. The previous code can be written this way.

var intString = "1111";

if(int.TryParse(intString, out int
i))
{
   
// it's integer
}
else
{
   
// it's not integer
}

NB! Use this trick if you are using out variable near where it is defined. If you need this variable also in other blocks that follow the declaring block then better go with traditional out variable.

Using var

But we don’t have to specify the type of out variable directly. Compiler can find it for us and this means we can also go with var. The next piece of code is the same as previous one.

var intString = "1111";

if(int.TryParse(intString, out var
i))
{
   
// it's integer
}
else
{
   
// it's not integer
}

NB! Here loose nothing when using var as it is easy to see that out type will be int. For other methods with out variables like those you can find when using P/Invoke need actual type to be written out if the same line doesn’t communicate it clearly.

Skipping out variable

Sometimes we don’t need out variable at all. Good example is removing elements from concurrent dictionary. Here is the fragment of code from my ASP.NET Core WebSocket chat room example. In WebSocket middleware class I have to remove the instance of socket from concurrent dictionary _sockets.

WebSocket dummy;
_sockets.TryRemove(socketId,
out
dummy);

await currentSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "Closing", ct);
currentSocket.Dispose();

When removing the socket I’m not interested of getting the instanceof it  because I already have it. On C# 7.0 we can skip out variable by replacing it with underscore.

_sockets.TryRemove(socketId, out _);

NB! ConcurrectDictionary<T,U> has TryRemove() method like this for certain reasons and it is not design flaw.

Using out variable skipping we can easily write code to check if string value can be turned to integer or not.

if(int.TryParse(intString, out _))
{
   
// it's integer
}

Behind the compiler

Let’s take a look what compiler actually produces if we build method that uses out variable skipping. Here is the method:

static void Main(string[] args)
{
   
var intString = "1111"
;

   
if(int.TryParse(intString, out
_))
    {
       
// it's integer
    }
   
else
    {
       
// it's not integer
    }

   
Console.ReadLine();
}

Now let’s build the program and open resulting DLL in JetBrains dotPeek.

private static void Main(string[] args)
{
   
int
result;
   
if (!int.TryParse("1111", out
result))
        ;
   
Console.ReadLine();
}

We get straight back to the roots.

Wrapping up

Out variables that are used in same block with TrySomething() method can now be declared inline where these variables are used in method call. Also keyword var is supported. Inline declarations of out variables lead us to cleaner code but we may loose readibility if these out variables are used also in other code blocks. Out variable skipping is good option when we don’t care about value of out variable. Like with everything else in coding there is one suggestion: use these features carefully and only if you benefit something from them.

Gunnar Peipman

Gunnar Peipman is ASP.NET, Azure and SharePoint fan, Estonian Microsoft user group leader, blogger, conference speaker, teacher, and tech maniac. Since 2008 he is Microsoft MVP specialized on ASP.NET.

    101 thoughts on “Out variables in C# 7.0

    • October 24, 2017 at 6:42 pm
      Permalink

      It’s a nice new feature, but unfortunately of limited use in more complicated situations. For instance, ‘if (TryThis || TryThat) { … }’ results in a CS0165 ‘use of unassigned local variable’ error when attempting to use the out variable from the TryThat statement. It’s clear why this happens — TryThat can be short-circuited if TryThis returns false — but means one has to fall back on explicit declaration of the out variables.

    • June 29, 2025 at 2:29 am
      Permalink

      With havin so much content do you ever run into any problems of plagorism or copyright
      infringement? My blog has a lot of unique content I’ve either
      written myself or outsourced but iit seems a lot of it is popping it up all over the internet without mmy agreement.
      Do you know any methods to help reduce content feom being ripped off?I’d genuinely apprecxiate it.

    • June 29, 2025 at 4:21 am
      Permalink

      No matter if some one searches for his vital thing, so he/she desires to be available that in detail, thus that thing is maintained over here.

    • June 29, 2025 at 11:54 am
      Permalink

      What’s Happening i’m new to this, I stumbled upon this I’ve discovered It positively useful and it
      has aided me out loads. I hope to contribute &
      assist different customers like its aided me.
      Great job.

    • June 29, 2025 at 12:14 pm
      Permalink

      05 August 2013 (Urgent: Stop promoting neonicotinoid pesticides)
      Within the US: name on US shops to stop promoting neonicotinoid pesticides.
      As neonicotinoid pesticides enter the soil and rivers, we
      do not know what species they are killing off. 06 August 2013 (Global Heating pushing
      marine species toward the poles) Global heating is pushing marine species in the
      direction of the poles at around four miles a yr.
      Since the poles are warming quickest, species that at the moment are too scorching at
      polar latitudes, equivalent to polar bear and harp seals and
      penguins soon will not have any place to go. Meanwhile, if you live in a spot which doesn’t have this policy, please fill out the form to be
      an organ donor, as I have performed. Oh, well.
      Like I mentioned I’m fairly excited for my first Autumn out
      of school. A vat-grown hamburger is a primary step towards producing meat without animals.

      5-Had concept that I may sneak 23 into her cryo-mattress if she fell asleep in a protected space first.
      Moreover, there may be the thought of what I name, the “Pink Aquarium”.
      If the current government is merciless to them too, there is
      no cause to spend a dime, or a life, to defend it.

    • June 30, 2025 at 4:31 am
      Permalink

      I am not sure where you’re getting your info,
      but great topic. I needs to spend some time learning more
      or understanding more. Thanks for wonderful info I was looking for this info for my mission.

    • June 30, 2025 at 7:09 am
      Permalink

      Hi, I do think this is a great blog. I stumbledupon it ;) I
      will revisit yet again since I book marked
      it. Money and freedom is the greatest way to change, may you be rich and continue
      to help other people.

    • June 30, 2025 at 11:43 am
      Permalink

      Today, while I was at work, my cousin stole my iphone and tested to
      see if it can survive a 25 foot drop, just so she can be a youtube sensation. My iPad is now destroyed and she has 83
      views. I know this is completely off topic but I had
      to share it with someone!

    • June 30, 2025 at 5:07 pm
      Permalink

      What’s Going down i am new to this, I stumbled upon this I
      have discovered It positively helpful and it has aided me out loads.
      I am hoping to contribute & assist other users like its aided me.
      Great job.

    • July 3, 2025 at 4:20 pm
      Permalink

      Hi there! I could have sworn I’ve been to this blog before but after looking at many of the articles I realized it’s new to me.

      Regardless, I’m certainly pleased I stumbled upon it and I’ll be bookmarking it and checking back often!

    • July 4, 2025 at 2:06 am
      Permalink

      Vivez l’expérience musicale Ԁe Wonny Song, pianiste
      inspiré dpnt chaque interprétation еѕt une histoire émotionnelle.

    • July 5, 2025 at 2:07 am
      Permalink

      hey there and thank you for your info – I have definitely picked up something new from right here.
      I did however expertise several technical points using this web site, as
      I experienced to reload the web site many times previous
      to I could get it to load properly. I had been wondering if
      your hosting is OK? Not that I am complaining, but sluggish loading instances times will often affect
      your placement in google and could damage your quality score if
      ads and marketing with Adwords. Well I’m adding
      this RSS to my email and can look out for much more of your respective fascinating content.
      Ensure that you update this again soon.

    • July 13, 2025 at 5:46 am
      Permalink

      Expeert WordPress website designers іn London. Offering
      custoom WordPresss designs, SEO strategies, аnd professional support tߋo increase yoսr online preence annd sales.

    • July 13, 2025 at 6:00 am
      Permalink

      Secure caravan, car, motorhome, and self storage іn Littlehampton, West Sussex.
      Serving Chichester, Bognor Regis, аnd Worthing.

      Afforable contaijer storage near you.

    • July 16, 2025 at 3:04 am
      Permalink

      Cabinet IQ
      15030 N Tatum Blvd #150, Phoenix,
      AZ 85032, United Ѕtates
      (480) 424-4866
      bookmarks

    • July 16, 2025 at 7:02 am
      Permalink

      Cabinet IQ
      15030 N Tatum Blvd #150, Phoenix,
      AZ 85032, United Տtates
      (480) 424-4866
      Painted

    • July 18, 2025 at 3:22 am
      Permalink

      Lookіng for affordable storage units? Check ᧐ut Container
      Storage Units fοr affordable options аcross Kent annd Surrey.

      Great fоr households ɑnd commercial use alike.

    • July 18, 2025 at 4:17 am
      Permalink

      Cabinet IQ
      15030 N Tatum Blvd #150, Phoenix,
      AZ 85032, United Ⴝtates
      (480) 424-4866
      DIYguide

    • July 19, 2025 at 1:09 pm
      Permalink

      I love lookling through a post that can make people think.
      Also, thank you for permitting me to comment!

      Also visit my site – Candace

    • July 19, 2025 at 1:35 pm
      Permalink

      Cabinet IQ
      15030 N Tatum Blvd #150, Phoenix,
      AZ 85032, United Ѕtates
      (480) 424-4866
      Bookmarks

    • July 19, 2025 at 1:38 pm
      Permalink

      Cabinet IQ McKinney
      3180 Eldrado Pkwy STE 100, McKinney,
      TX 75072, Unites Ꮪtates
      (469) 202-6005
      veneer

    • July 19, 2025 at 2:37 pm
      Permalink

      Cabinet IQ McKinney
      3180 Eldorado Pkwy STE 100, McKinney,
      TX 75072, Unites Ѕtates
      (469) 202-6005
      finish

    • July 19, 2025 at 7:34 pm
      Permalink

      Loօking for reliable EV charger installwtion іn Durham, Newcastle, ɑnd Sunderland?
      Book ᴡith Green Spark Electrics t᧐dаy. Unlesash the power of the lates technology іn EV charging
      wіth Green Spark Electrics, your trusted paetner iin Durham, Newcastle, annd Sunderland.
      Ꮃhat mwkes Green Spark Electrics stand οut? We aгe dedicated to providing the best in EV chargger installations,
      offering advanced solutions tailored tⲟ both residential аnd commercial neеds.

    • July 20, 2025 at 12:28 am
      Permalink

      Laissez-νous séduire pɑr l’univers pianistique
      ɗe Wonny Song, où chaquе mélodie éveille émotions еt passion.

    • July 20, 2025 at 12:49 am
      Permalink

      Cabinet IQ McKinney
      3180 Eldorado Pkwy STE 100, McKinney,
      TX 75072, Unites Ѕtates
      (469) 202-6005
      Farmhouse

    • July 20, 2025 at 8:22 am
      Permalink

      Cabinet IQ
      15030 N Tatum Blvd #150, Phoenix,
      AZ 85032, United Ꮪtates
      (480) 424-4866
      customfit

    • July 20, 2025 at 2:29 pm
      Permalink

      I know this web pazge presents quality depending articles and additional
      data, is there any other web site which presents these data in quality?

    • July 20, 2025 at 2:45 pm
      Permalink

      This is a topic which is near to my heart…
      Many thanks! Exactly where are your contact details though?

    • July 20, 2025 at 11:10 pm
      Permalink

      Transform your skin at HSA Dermal Clinic with cutting-edge aesthetic procedures.

    • July 21, 2025 at 3:28 pm
      Permalink

      Article writing is also a fun, if you be acquainted
      with afterward you can write or else it is complicated to write.

    • July 23, 2025 at 11:01 pm
      Permalink

      My spouse and I absolutely love your blog and find a lot
      of your post’s to be just what I’m looking for. Would you offer guest writers to write content for yourself?
      I wouldn’t mind producing a post or elaborating on some of the
      subjects you write about here. Again, awesome site!

      Feel free to surf to my blog: Discovery Kingdom Coupons

    • July 25, 2025 at 4:42 am
      Permalink

      The Elevi Medical Aesthetics website provides a clean and modern website that’s user-friendly.
      The treatments are outlined clearly, and the look
      conveys credibility, care, and a focus on beauty and wellness.

    • July 25, 2025 at 2:01 pm
      Permalink

      I constantly emailed this website post page to all my associates, as if like to read it
      afterward my links will too.

    • July 25, 2025 at 8:19 pm
      Permalink

      NewStartForMe delivers a uplifting and supportive space
      for personal growth. The simple layout, insightful
      content, and inspiring approach make it a strong starting point.

    • July 26, 2025 at 1:57 pm
      Permalink

      The Xtreme Heating and Cooling website is neatly structured, credible, and easy to navigate.
      It features their offerings, inspires confidence,
      and reflects a strong dedication to quality HVAC solutions.

    • July 26, 2025 at 11:50 pm
      Permalink

      The Dohodigital website offers a sleek and intuitive experience with valuable digital marketing insights.
      The design is clear and reliable.

    • July 27, 2025 at 10:18 am
      Permalink

      The researchers used a hydrogel to 3D-print a model of the
      corpus cavernosum – a key structure in the penis that fills with blood during an erection. Next,
      they seeded this scaffold with endothelial cells – the main cells that line blood vessels

    • July 28, 2025 at 5:03 am
      Permalink

      It is not possible to become uncircumcised, as circumcision is a surgical procedure that removes the foreskin from
      the penis.

    • July 28, 2025 at 7:40 am
      Permalink

      Concert Attire Stamford
      360 Fairfield Ave,
      Stamford, CT 06902, United Ꮪtates
      +12033298603
      Visor

    • July 30, 2025 at 5:18 am
      Permalink

      It’s generally advisable to consult a healthcare professional before taking any medication, including
      decongestants, after a concussion.

    • July 30, 2025 at 8:36 am
      Permalink

      American Windows & Siding
      4227 Centergate Ѕt, San Antonio
      TX 78217, United Stɑtes
      12109715766
      Bookmarks

    • July 31, 2025 at 12:17 am
      Permalink

      Wow, wonderful weblog layout! How long have you ever been blogging for?
      you make blogging glance easy. The whole glance of your website is excellent, let alone the content!

    • July 31, 2025 at 2:58 am
      Permalink

      I’m not that much of a internet reader to be honest but your blogs really
      nice, keep it up! I’ll go ahead and bookmark your site to come back
      later on. Many thanks

      Here is my web site – Geng WD

    • July 31, 2025 at 10:23 am
      Permalink

      Greetings! I know this is kinda off topic but I’d figured I’d
      ask. Would you be interested in exchanging links or maybe guest
      authoring a blog article or vice-versa? My blog goes over a lot of the same
      subjects as yours and I believe we could greatly benefit from each other.
      If you are interested feel free to send me an e-mail. I look forward to hearing from you!
      Great blog by the way!

    • July 31, 2025 at 11:04 am
      Permalink

      Hi, Neat post. There’s an issue together with your website in internet explorer, would test this?

      IE still is the market chief and a large component
      to people will leave out your wonderful writing due to this problem.

    • August 5, 2025 at 6:47 am
      Permalink

      Johnson, who is 47 but has the body of a man in his 30s and the penile health of a 22 year old, told
      millions of his followers he takes a single dose of 2.

    • August 6, 2025 at 7:58 am
      Permalink

      Heya i am for the primary time here. Icame across this board and I find It really helpful & it helped me out much.
      I am hoping to give one thing again and help others like you aided me.

    • August 6, 2025 at 8:20 am
      Permalink

      Cabinet IQ McKinney
      3180 Eldorado Pkwy STE 100, McKinney,
      TX 75072, Unites Ѕtates
      (469) 202-6005
      Luxury

    • August 8, 2025 at 7:37 am
      Permalink

      What’s up to every body, it’s my first pay a visit of this weblog; this blog carries awesome and genuinely fine material designed for visitors.

    • August 8, 2025 at 8:13 am
      Permalink

      Mighty Dog Roofing
      Reimer Drive North 13768
      Maple Grove, MN 55311 United Ⴝtates
      (763) 280-5115
      reliable roof repair services, Shana,

    • August 8, 2025 at 8:50 am
      Permalink

      HorsePower Brands Omaha
      2525 N 117th Ave #300,
      Omaha, NE 68164, United Ѕtates
      14029253112
      Bookmarks

    • August 8, 2025 at 10:23 am
      Permalink

      Aw, this was ɑan extremely good рost. Ѕpending sоme time annd actual effort to create a very good article… but ѡhat can I saү… I put things
      off а whole lot and don’t manage to get narly anything Ԁone.

    • August 10, 2025 at 1:47 pm
      Permalink

      For hottest news you have to go to see world-wide-web
      and on internet I found this web page as a most excellent web page for most recent updates.

    • August 15, 2025 at 10:32 pm
      Permalink

      Howdy! I understand this is sort of off-topic but I needed to ask.
      Does operating a well-established blog such as yours require a lot of work?
      I am completely new to operating a blog but I do write in my journal everyday.
      I’d like to start a blog so I can share my experience and
      views online. Please let me know if you have any recommendations or tips
      for new aspiring bloggers. Thankyou!

    • August 16, 2025 at 2:03 am
      Permalink

      It’s fantastic that you are getting ideas from this piece of writing as well as from our dialogue made
      at this place.

    • August 16, 2025 at 2:34 am
      Permalink

      Refresh Renovation Southwest Charlotte
      1251 Arrow Pine Ɗr c121,
      Charlotte, NC 28273, United Ѕtates
      +19803517882
      Annd Laundry Kitgchen Ѕmall remodel; atavi.com,

    • August 16, 2025 at 10:14 pm
      Permalink

      Greetings! Quick question that’s totally off topic. Do you know
      how to make your site mobile friendly? My web site looks weird when viewing from my iphone 4.
      I’m trying to find a template or plugin that might be able to resolve
      this problem. If you have any suggestions, please share.
      Many thanks!

    • August 16, 2025 at 10:53 pm
      Permalink

      Refresh Renovation Southwest Charlotte
      1251 Arrow Pine Ꭰr c121,
      Charlotte, NC 28273, United Ꮪtates
      +19803517882
      And conversion loft attic – padlet.com

    • August 19, 2025 at 12:32 am
      Permalink

      I have been browsing online more than 3 hours today, yet I never found any interesting article like
      yours. It’s pretty worth enough for me. Personally, if all site owners
      and bloggers made good content as you did, the net will be a lot more useful than ever before.

    • August 20, 2025 at 11:10 pm
      Permalink

      Hi there to every , because I am actually eager of reading this web site’s post to be updated on a regular basis.

      It contains good data.

    • August 22, 2025 at 2:17 am
      Permalink

      I’ve been browsing on-line more than 3 hours as of late, yet I never
      discovered any interesting article like yours. It’s pretty value sufficient
      for me. Personally, if all website owners and bloggers made excellent content material as
      you probably did, the internet shall be much more useful than ever before.

    • August 26, 2025 at 11:42 pm
      Permalink

      It’s in reality a great and helpful piece of information.
      I am satisfied that you just shared this useful info with us.

      Please keep us informed like this. Thank you for sharing.

    • August 27, 2025 at 6:46 am
      Permalink

      Hello, i read your blog occasionally and i own a similar one
      and i was just wondering if you get a lot of spam remarks?

      If so how do you prevent it, any plugin or anything you can advise?
      I get so much lately it’s driving me mad so any support is very much appreciated.

    • August 30, 2025 at 9:33 pm
      Permalink

      No matter if some one searches for his vital thing, so he/she wishes to
      be available that in detail, thus that thing is maintained over here.

    • August 31, 2025 at 4:34 am
      Permalink

      wonderful issues altogether, you simply won a brand new reader.
      What could you suggest in regards to your put up that you just made a few days ago?
      Any sure?

    • September 7, 2025 at 6:05 am
      Permalink

      If you are going for best contents like me, only
      pay a quick visit this web site all the time because it presents quality contents, thanks

    • September 13, 2025 at 2:23 am
      Permalink

      This blog was… how do you say it? Relevant!! Finally I’ve found
      something which helped me. Cheers!

    Leave a Reply

    Your email address will not be published. Required fields are marked *