简体   繁体   中英

How to use namespace for a limited part of the code

I want to use namespace System.Security.Cryptography but only for a limited part of the code so that if I will try to use the namespace's classes or function out of the defined area it won't work. the result I'm expecting is something similar to the using statement in types , but with namespaces .

here is a sample code to showcase what I want:

using(System.Security.Cryptography;){
// namespace can be used from now on
            using (MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider())
            {
                UTF8Encoding utf8 =new UTF8Encoding();
                byte[] data = md5.ComputeHash(utf8.GetBytes(input));
                return Convert.ToBase64String(data);
            }
}
//now namespace can not be used- error if you are trying to use it

is it possible to do and how?

Put it in using, or just use eg:

System.Security.Cryptography.MD5CryptoServiceProvider

Then no need for using.

My point is:

 using (System.Security.Cryptography.MD5CryptoServiceProvider md5 = new System.Security.Cryptography.MD5CryptoServiceProvider())
 {
     System.Text.UTF8Encoding utf8 = new System.Text.UTF8Encoding();
     byte[] data = md5.ComputeHash(utf8.GetBytes(input));
     return Convert.ToBase64String(data);
 }

Hope you get it now :)

I suggest using full qualified name System.Security.Cryptography.MD5CryptoServiceProvider instead of using + short name ( MD5CryptoServiceProvider ):

  // var - let compiler derive the type
  using (var md5 = new System.Security.Cryptography.MD5CryptoServiceProvider())
  {
      UTF8Encoding utf8 = new UTF8Encoding();
      byte[] data = md5.ComputeHash(utf8.GetBytes(input));
      return Convert.ToBase64String(data);
  }

If you do this, you'll not have to put using System.Security.Cryptography; at all

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM