Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Example implementation of 'TryParse' or 'TryGetValue' [closed]

Can you give me an example of implementation of .NET 'try' pattern?

Edit:

I don't mean a "try-catch" statement, I mean a try patterns, like those used in TryParse(), and TryGetObjectByKey() methods.

Most specifically what to do with raised exceptions in custom 'try' pattern methods. Should I log it, should I ignore It. Does' anybody know what is the practice with those methods?

like image 655
kofucii Avatar asked Oct 03 '10 15:10

kofucii


People also ask

How does TryParse work?

TryParse(String, Int32) Converts the string representation of a number to its 32-bit signed integer equivalent. A return value indicates whether the conversion succeeded.

What does TryGetValue do?

TryGetValue Method: This method combines the functionality of the ContainsKey method and the Item property. If the key is not found, then the value parameter gets the appropriate default value for the value type TValue; for example, 0 (zero) for integer types, false for Boolean types, and null for reference types.

What is the use of TryGetValue in C #?

Use the TryGetValue method if your code frequently attempts to access keys that are not in the dictionary. Using this method is more efficient than catching the KeyNotFoundException thrown by the Item[] property. This method approaches an O(1) operation.

Why use TryParse in c#?

In C#, Char. TryParse() is Char class method which is used to convert the value from given string to its equivalent Unicode character.


1 Answers

Here is an example of using a TryXxx method:

string s = Console.ReadLine(); int x; if (int.TryParse(s, out x)) {     Console.WriteLine("You entered the valid integer {0}", x); } else {     Console.WriteLine("Invalid input!"); } 

Here is an example of defining the method:

bool TryParse(string s, out int x)  // out parameter for result {     if (!allCharactersAreValid(s))     {         x = 0;         return false;     }      // More checks...     // Parse the string...      x = 42;     return true; } 

Exception handling

Most specificly what to do with rised exceptions in custom 'try' pattern methods

Your method probably should avoid throwing any exceptions - if your user wanted exceptions they would use the non-Try version. You should therefore try to avoid calling methods which can throw when implementing your TryXxx. However some exceptions are unavoidable and could be thrown out of your control - for example OutOfMemoryException, StackOverflowException, etc... There is nothing you can do about this and you should not try to catch these exceptions, just let them propagate to the caller. Don't swallow them, don't log them - that's the caller's responsibility.

An example of this is Dictionary<TKey, TValue>.TryGetValue when the key object provided to this method throws an exception when GetHashCode is called. Then the resulting exception is not caught inside the TryGetValue method - the caller will see the exception. This code demonstrates this happening:

using System; using System.Collections.Generic;  class Foo {     public override int GetHashCode()     {         throw new NotImplementedException();     } }  class Program {     public static void Main()     {         Dictionary<object, object> d = new Dictionary<object, object>();         d["bar"] = 42;          object s;         Foo foo = new Foo();         if (d.TryGetValue(foo, out s))   // results in NotImplementedException         {             Console.WriteLine("found");         }     } } 
like image 144
Mark Byers Avatar answered Sep 24 '22 00:09

Mark Byers