Sunteți pe pagina 1din 8

Articles from Jinal Desai .

NET
.NET Framework 4.5 New Features Interview Questions
2013-09-27 07:09:14 Jinal Desai

1. Can we develop Windows Store Apps using .NET Framework 4.5? Ans. Yes, there is subset of managed types available with .NET Framework 4.5 to develop Windows Store Apps. Using these managed types we can develop Windows Store Apps with our favorite language C# or Visual Basic. These managed types resides in namespaces starts with System and the Windows Runtime types reside in namespaces that starts with Windows together make framework for development of Windows Store Apps. 2. I have developed one collection of classes and I want to reuse the same across multiple applications like silverlight application, windows phone application, Windows 7 or Windows 8 application. Is it possible? Ans. Yes, with .NET Framework 4.5 it is possible to do cross-platform development. Previously we need to rewrite required classes for multiple framework, but now in .NET Framework 4.5 support Portal Class Library. Using portable class library you can develop your business logic classes and use them across multiple platforms without need to do any kind of changes. 3. What is the element we can use in application configuration file to define arrays larger than 2GB on 64-bit OS? Ans. To define arrays larger than 2GB on 64-bit OS we can use gcAllowVeryLargeObjects element and set its enabled attribute to true. <gcAllowVeryLargeObjects enabled="true" /> 4. What is the performance improvement come for garbage collection with .NET Framework 4.5? Ans. With .NET Framework 4.5 background garbage collection is automatically enabled for servers for performance improvement. 5. How .NET Framework 4.5 reducing system restarts during installation? Ans. The .NET Framework 4.5 uses the Restart Manager to avoid system restarts whenever possible during installation. The .NET Framework 4.5 requires system restart if any .NET Framework 4 application is in use during installation because .NET Framework 4.5 replaces .NET Framework 4 files which requires those files to be available during installation. Restart Manager prevents restart by detecting and closing .NET Framework 4 applications that are in use. During installation it will prompt you list of .NET Framework 4 applications in use and give option to close these application before proceeding with installation. If confirms by user, these applications are shut down by the installer and system restarts avoided. If user does responds in certain amount of time, installer continues without closing any applications. In extreme cases system restarts is required even if running applications are closed. 6. How we can take advantage of background just-in-time (JIT) compilation feature of .NET Framework 4.5? Ans. On multi-core processors to improve application performance background just-in-time compilation is available to be utilized optionally. We can achieve this using ProfileOptimization class. ProfileOptimization class improves the startup performance of application domains in applications that require the just-in-time (JIT) compiler by performing background compilation of methods that are likely to be executed, based on profiles created during previous compilations. using System.Runtime; class Program { static void Main() { // Profiles directory must exist. // "MyProfile" is created. ProfileOptimization.SetProfileRoot("D:\\ProfileCollection\\Profiles\\"); ProfileOptimization.StartProfile("MyProfile"); } } Here, SetProfileRoot Enables optimization profiling for the current application domain, and sets the folder where the optimization profile files are stored. On a single-core computer, the method is ignored and StartProfile Starts just-in-time (JIT) compilation of the methods that were previously recorded in the specified profile file, on a background thread. Starts the process of recording current method use, which later overwrites the specified profile file. Note: Profile optimization requires a multicore computer. The methods are ignored on other computers.

7. Can you explain the usefulness of new property Regex.MatchTimeout introduced by .NET Framework 4.5? Ans. There are times when being able to limit the pattern matching duration of Regex operations could be useful, especially when working with user supplied patterns to match data. The MatchTimeout property defines the approximate maximum time interval for a Regex instance to execute a single matching operation before the operation times out. The regular expression engine throws a RegexMatchTimeoutException exception during its next timing check after the time-out interval has elapsed. This prevents the regular expression engine from processing input strings that require excessive backtracking. This property is read-only. You can set its value explicitly for an individual Regex object by calling the Regex.Regex(String, RegexOptions, TimeSpan) constructor; and you can set its value for all Regex matching operations in an application domain by calling the AppDomain.SetData method and providing a value for the REGEX_DEFAULT_MATCH_TIMEOUT property. If you do not explicitly set a timeout interval, the default value Regex.InfiniteMatchTimeout is used, and matching operations do not time out. string input = "The quick brown fox jumps over the lazy dog."; string pattern = @"([a-z ]+)*!"; try { bool result = Regex.IsMatch(input, pattern, RegexOptions.None, TimeSpan.FromSeconds(4)); } catch (RegexMatchTimeoutException ex) { Console.WriteLine("Match timed out!"); Console.WriteLine("- Timeout interval specified: " + ex.MatchTimeout); Console.WriteLine("- Pattern: " + ex.Pattern); Console.WriteLine("- Input: " + ex.Input); } catch (Exception ex) { Console.WriteLine(ex.Message); } 8. Is it possible to define default culture for an application domain? How? Ans. Inside the application domain when threads get created, threads gets default culture from windows initialized from the system default locale as configured in control panel > region and language settings. But with .NET Framework 4.5 it is possible to provide default culture for an application domain using DefaultThreadCurrentCulture and DefaultThreadCurrentUICulture properties of CultureInfo class. Following is example for the same. public static void Main() { Console.OutputEncoding = Encoding.UTF8; // Change current culture CultureInfo culture; if (Thread.CurrentThread.CurrentCulture.Name == "fr-FR") culture = CultureInfo.CreateSpecificCulture("en-US"); else culture = CultureInfo.CreateSpecificCulture("fr-FR"); CultureInfo.DefaultThreadCurrentCulture = culture; CultureInfo.DefaultThreadCurrentUICulture = culture; Thread.CurrentThread.CurrentCulture = culture; Thread.CurrentThread.CurrentUICulture = culture; // Generate and display three random numbers on the current thread. DisplayRandomNumbers(); Thread.Sleep(1000); Thread workerThread = new Thread(new ThreadStart(Example.DisplayRandomNumbers)); workerThread.Start(); } private static void DisplayRandomNumbers() { Console.WriteLine(); Console.WriteLine("Current Culture: {0}", Thread.CurrentThread.CurrentCulture); Console.WriteLine("Current UI Culture: {0}", Thread.CurrentThread.CurrentUICulture); Console.Write("Random Values: "); Random rand = new Random();

for (int ctr = 0; ctr <= 2; ctr++) Console.Write(" {0:C2} ", rand.NextDouble()); Console.WriteLine(); } // Output: // Current Culture: // Current UI Culture: // Random Values: // // Current Culture: // Current UI Culture: // Random Values:

fr-FR fr-FR 0,78 fr-FR fr-FR 0,52

0,80

0,37

0,32

0,15

9. What is the purpose of SortVersion class? How it affects string comparison and ordering operations? Ans. From the .NET Framework 2.0 Service Pack 1 through the .NET Framework 4, each version of the.NET Framework has included tables that contain sort weights and data on string normalization and that are based on a particular version of Unicode. In the .NET Framework 4.5, the presence of these tables depends on the operating system: On Windows 7 and previous versions of the Windows operating system, the tables continue to be used for comparing and ordering strings. On Windows 8, the .NET Framework delegates string comparison and ordering operations to the operating system. Consequently, the result of a string comparison can depend not only on the .NET Framework version, but also on the operating system version, as the following table shows.

.NET Framework version Operating system Unicode version


.NET Framework 4 NET Framework 4.5 NET Framework 4.5 All operating systems Unicode 5.0 Windows 7 Windows 8 Unicode 5.0 Unicode 6.0

On Windows 8, because the version of Unicode used in string comparison and ordering depends on the version of the operating system, the results of string comparison may differ even for applications that run on a specific version of the .NET Framework. The SortVersion class provides information about the Unicode version used by the .NET Framework for string comparison and ordering. It enables to write applications that can detect and successfully handle changes in the version of Unicode that is used to compare and sort an applications strings. The following example contains a portion of the source code from an application that uses the SortVersion class to ensure that the native names of RegionInfo objects are ordered appropriately for the current system and current culture. public class Example : IComparer { private const string FILENAME = @".\Regions.dat"; private struct Region { internal Region(string id, string name) { this.Id = id; this.NativeName = name; } public string Id; public string NativeName; public override string ToString() { return this.NativeName; } } public static void Main() { bool reindex = false; Region[] regions; SortVersion ver = null; // If the data has not been saved, create it. if (! File.Exists(FILENAME)) {

regions = GenerateData(); ver = CultureInfo.CurrentCulture.CompareInfo.Version; reindex = true; } // Retrieve the existing data. else { regions = RestoreData(out ver); } // Determine whether the current ordering is valid; if not, reorder. if (reindex || ver != CultureInfo.CurrentCulture.CompareInfo.Version) { Array.Sort(regions, new Example()); // Save newly reordered data. SaveData(regions); } // Continue with application... } private static Region[] GenerateData() { List<Region> regions = new List<Region>(); foreach (var culture in CultureInfo.GetCultures(CultureTypes.AllCultures)) { if (culture.IsNeutralCulture | culture.Equals(CultureInfo.InvariantCulture)) continue; RegionInfo region = new RegionInfo(culture.Name); regions.Add(new Region(region.Name, region.NativeName)); } return regions.ToArray(); } private static Region[] RestoreData(out SortVersion ver) { List<Region> regions = new List<Region>(); BinaryReader binaryReader = new BinaryReader(File.Open(FILENAME, FileMode.Open)); int sortVer = binaryReader.ReadInt32(); Guid sortId = Guid.Parse(binaryReader.ReadString()); ver = new SortVersion(sortVer, sortId); string id, name; while (binaryReader.PeekChar() != -1) { id = binaryReader.ReadString(); name = binaryReader.ReadString(); regions.Add(new Region(id, name)); } return regions.ToArray(); } private static void SaveData(Region[] regions) { SortVersion sortVersion = CultureInfo.CurrentCulture.CompareInfo.Version; BinaryWriter binaryWriter = new BinaryWriter(File.Open(FILENAME, FileMode.Create)); binaryWriter.Write(sortVersion.FullVersion); binaryWriter.Write(sortVersion.SortId.ToString()); foreach (var region in regions) { binaryWriter.Write(region.Id); binaryWriter.Write(region.NativeName); } binaryWriter.Close(); } public int Compare(object o1, object o2) { // Assume that all casts succeed. Region r1 = (Region) o1; Region r2 = (Region) o2; return String.Compare(r1.NativeName, r2.NativeName, StringComparison.CurrentCulture); } } 10. How to customize a reflection context to override default reflection behavior?

Ans. We can achieve this using CustomReflectionContext class. provides a way for you to add or remove custom attributes from reflection objects, or add dummy properties to those objects, without re-implementing the complete reflection model. The default CustomReflectionContext simply wraps reflection objects without making any changes, but by subclassing and overriding the relevant methods, you can add, remove, or change the attributes that apply to any reflected parameter or member, or add new properties to a reflected type. For example, suppose the code follows the convention of applying a particular attribute to factory methods, but we are now required to work with third-party code that lacks attributes. We can use CustomReflectionContext to specify a rule for identifying the objects that should have attributes and to supply the objects with those attributes when they are viewed from our code. Note: To use CustomReflectionContext effectively, the code that uses the reflected objects must support the notion of specifying a reflection context, instead of assuming that all reflected objects are associated with the runtime reflection context. Many reflection methods in the .NET Framework provide a ReflectionContext parameter for this purpose. To modify the attributes that are applied to a reflected parameter or member, override the GetCustomAttributes(ParameterInfo, IEnumerable) or GetCustomAttributes(MemberInfo, IEnumerable) method. These methods take the reflected object and the list of attributes under its current reflection context, and return the list of attributes it should have under the custom reflection context. //A blank example attribute. class myAttribute : Attribute { } //Reflection context with custom rules. class myCRC : CustomReflectionContext { //Called whenever the reflection context checks for custom attributes. protected override IEnumerable<object> GetCustomAttributes(MemberInfo member, IEnumerable<object> declaredAttributes) { //Add example attribute to "To*" members. if (member.Name.StartsWith("To")) { yield return new myAttribute(); } //Keep existing attributes as well. foreach (var attr in declaredAttributes) yield return attr; } } class Program { static void Main(string[] args) { myCRC mc = new myCRC(); Type t = typeof(String); //A representation of the type in the default reflection context. TypeInfo ti = t.GetTypeInfo(); //A representation of the type in the customized reflection context. TypeInfo myTI = mc.MapType(ti); //Display all the members of the type and their attributes. foreach (MemberInfo m in myTI.DeclaredMembers) { Console.WriteLine(m.Name + ":"); foreach (Attribute cd in m.GetCustomAttributes()) { Console.WriteLine(cd.GetType()); } } Console.WriteLine(); //The "ToString" member as represented in the default reflection context. MemberInfo mi1 = ti.GetDeclaredMethods("ToString").FirstOrDefault(); //All the attributes of "ToString" in the default reflection context. Console.WriteLine("'ToString' Attributes in Default Reflection Context:");

foreach (Attribute cd in mi1.GetCustomAttributes()) { Console.WriteLine(cd.GetType()); } Console.WriteLine(); //The same member in the custom reflection context. mi1 = myTI.GetDeclaredMethods("ToString").FirstOrDefault(); //All its attributes, for comparison. myAttribute is now included. Console.WriteLine("'ToString' Attributes in Custom Reflection Context:"); foreach (Attribute cd in mi1.GetCustomAttributes()) { Console.WriteLine(cd.GetType()); } Console.ReadLine(); } } 11. Can you explain UseRandomizedStringHashAlgorithm configuration attribute introduced in .NET Framework 4.5? Ans. By default, the StringComparer class and the String.GetHashCode method use a single hashing algorithm that produces a consistent hash code across application domains. This is equivalent to setting the enabled attribute of the element to 0. This is the hashing algorithm used in the .NET Framework 4. The StringComparer class and the String.GetHashCode method can also use a different hashing algorithm that computes hash codes on a per application domain basis. As a result, hash codes for equivalent strings will differ across application domains. This is an opt-in feature; to take advantage of it, you must set the enabled attribute of the element to 1. //<configuration> // <runtime> // <UseRandomizedStringHashAlgorithm enabled="1" /> // </runtime> //</configuration> public class Example { public static void Main() { // Show hash code in current domain. DisplayString display = new DisplayString(); display.ShowStringHashCode(); // Create a new app domain and show string hash code. AppDomain domain = AppDomain.CreateDomain("NewDomain"); var display2 = (DisplayString) domain.CreateInstanceAndUnwrap(typeof(Example).Assembly.FullName, "DisplayString"); display2.ShowStringHashCode(); } } public class DisplayString : MarshalByRefObject { private String s = "This is a string."; public override bool Equals(Object obj) { String s2 = obj as String; if (s2 == null) return false; else return s == s2; } public bool Equals(String str) { return s == str; } public override int GetHashCode() { return s.GetHashCode(); } public override String ToString() {

return s; } public void ShowStringHashCode() { Console.WriteLine("String '{0}' in domain '{1}': {2:X8}", s, AppDomain.CurrentDomain.FriendlyName, s.GetHashCode()); } } //Output //String //String //Output //String //String when <UseRandomizedStringHashAlgorithm enabled="0" /> 'This is a string.' in domain 'PerDomain.exe': 941BCEAC 'This is a string.' in domain 'NewDomain': 941BCEAC when <UseRandomizedStringHashAlgorithm enabled="1" /> 'This is a string.' in domain 'PerDomain.exe': 5435776D 'This is a string.' in domain 'NewDomain': 75CC8236

12. Can you explore async and await keywords? Ans. Async and Await keywords used for asynchronous programming in C# or VB. Following is example for the same. static void Main(string[] args) { Method1(); Console.WriteLine("Main Thread"); Console.ReadLine(); } public static void Method1() { Task.Run(new Action(Method2)); Console.WriteLine("New Thread"); } public static void Method2() { Thread.Sleep(10000); } Lets dry run above code. 1. Method1() gets called from the main thread. 2. Method1() spawns a Task named Method2() which waits for 10 seconds. 3. Same time the control comes back to Method1() to execute the remaining code after the task called. While Method2() waits for 10 seconds the remaining code of Method1() gets executed. Now lets modify the algorithm to use async and await. All other thing remains same except Method1(). public static async void Method1() { await Task.Run(new Action(Method2)); Console.WriteLine("New Thread"); } Now, the step 2 in our last dry run will only continue execution once step 2 completed its execution. You can also achieve the same with Task.Wait and Task.ContinueWith but Task.Wait will synchronously block until the task completes. So the current thread is literally blocked waiting for the task to complete. Await will asynchronously wait until the task completes. This means the current method is paused (its state is captured) and the method returns an incomplete task to its caller. Later, when the await expression completes, the remainder of the method is scheduled as a continuation. 13. Can I create zip file? How? Ans. Upto .NET Framework 4.5 we cannot create .zip files. In .NET Framework 4.5 it is now possible. Following is example for creating zip file and extracting zip file from and to folder. //using System.IO.Compression; //To zip ZipFile.CreateFromDirectory(@"d:\FolderToCompress",@"d:\FolderToCompress.zip"); //To unzip ZipFile.ExtractToDirectory(@"D:\FolderToCompress.zip", @"D:\FolderToCompress\UnzippedData"); .NET Framework 4.5 New Features Interview Questions 0.00 / 5 5 1/5

2/5 3/5 4/5 5/5


0 votes, 0.00 avg. rating ( 0% score)

S-ar putea să vă placă și