Monday, 21 July 2014

What is formatted output in asp.net? Or the difference between Response. Write () and Response.Output.Write () in ASP.NET.



The short answer is that the latter gives you String. Format-style output and the former doesn't. The long answer follows.

           In ASP.NET the Response object is of type HttpResponse and when you say Response.Writeyou're really saying (basically) HttpContext.Current.Response.Write and calling one of the many overloaded Write methods of HttpResponse. Response. Write then calls .Write () on its internal TextWriter object.

Response. Write ():
Display only string and you cannot display any other data type values like int, date, etc. Conversion (from one data type to another) is not allowed.

Response .Output .Write ():
You can display any type of data like int, date, string etc. By giving index values.

Example code:



protected void Button1_Click(object sender, EventArgs e)
{
 Response.Write ("hi good morning!"+"is it right?"); //only strings are allowed       
 Response.Write("Scott is {0} at {1:d}", "cool", DateTime.Now);//this will give
       //error(conversion is not allowed)
 Response.Output.Write ("\nhi goood morning!"); //works fine
 Response.Output.Write("Jai is {0} on {1:d}", "cool", DateTime.Now);//here the
       // current date will be converted into string and displayed
}

Difference: 

1) Response.Output.Write allows us to write a more formatted output: 


Example: 


Response.Output.Write ("hello {0}", "asp.net"); 
//It is Ok 

But, Response. Write ("hello {0}","asp.net"); 
//It is wrong 


2) As per ASP.NET 3.5, Response. Write has 4 overloads, while Response.Output.Write 

has 17 overloads.
 

Example: To write integer, double, Boolean values using Response. Write, we are 

provided with one overloaded version : Response. Write (object obj); 

to do the same thing using Response.Output.Write, we are provided with separate 

overloaded versions: 
 
ex: 1) Response.Output.Write (int s); 

2) Response.Output.Write (double s); 

3) Response.Output.Write (bool b);

FOR Example:



Response.Output.Write () gives you String. Format-style formatted output and the Response. Write () doesn't. 


Response. Write ("Current Date Time is "+DateTime.Now.ToString ()); 

Response.Output.Write ("{0} is {1:d}", "Current Date Time is: ",DateTime.Now);





No comments:

Post a Comment