Sunday, July 31, 2005

& and && in C# , part - I

There are 2 AND,OR operators in C# ( of course it exists in language like C++ or Java as well ), one is &, | and second one is &&, II , most of the time we work with the second one, first one is less popular in regualar programming, but the first one is more powerfull and usefull than the second one( my personal comments :) ).
As per MSDN documentation difference between them two is following ...

The conditional-AND operator (&&) performs a logical-AND of its bool operands, but only evaluates its second operand if necessary.
Binary & operators are predefined for the integral types and bool. For integral types, & computes the bitwise AND of its operands. For bool operands, & computes the logical AND of its operands; that is, the result is true if and only if both its operands are true.

The operation x && y corresponds to the operation x & y, except that y is evaluated only if x is true.
The operation x || y corresponds to the operation x | y, except that y is evaluated only if x is false.
Let me use the following code to explain it ....
int i = 0;
int j = 0;
if( false & ( ++i > 0 ) )
{
MessageBox.Show( "Inside if condition" );
}
if( false && ( ++j > 0) )
{
MessageBox.Show( "Inside if condition" );
}
MessageBox.Show( i.ToString() );
MessageBox.Show( j.ToString() );
guess what will be the value of i and j when MessageBox will show ... i will be 1 and j will be 0, since first if has used & so run time will evaluate both the operand( hence i will be increased by 1), but in case && as the first oeprand is FALSE it will not evaluate the scond one at all( hence value of j will remain 0 ), but none of them will show "Inside if condition".
I will write some more interesting facts of & operator in part II.

Note : in C++ we can use & as a unery operator. & gives the address of the operand.

Wednesday, July 27, 2005

Dangling Pointer

Last night I was trying my hand on C++ .... and I came across an interesting problem ...
all I was trying to do following
1) create a class ( say TestClass ) which will have an int variable( age ), and we can set value into this variable using 2 methods(set and get).
2) create a global scope pointer of this type in the file.( say m_TestClass ) ...
3) write a method( say createTestClassObject ) where I will create an object of the class "TestClass" and the pointer( m_TestClass ) will point to this object.
then I will do a set and get( printf ).
4) "createTestClassObject" method will be called from the main and after this method returns to main .. I will do another m_TestClass->getAge()( priintf ) .
This is what I have written ...( I have used .NET IDE )

#include "stdafx.h"
#include "stdio.h"
#include "iostream"
#include "conio.h"
#using
using namespace System;
using namespace std;

void createTestClassObject();


class TestClass
{
int m_Age;
public:
TestClass()
{
// dummy constructor
}

void setAge( int age )
{
m_Age = age;
}

int getAge()
{
return m_Age;
}
};

TestClass *m_TestClass;
int main()
{
createTestClassObject();
printf("\n%d", m_TestClass->getAge() );
int i = getch();
return 0;
}

void createTestClassObject()
{
TestClass obj;
m_TestClass = &obj;
m_TestClass ->setAge(100);
printf("\n%d", m_TestClass->getAge());
}

the output of the program is first 100 and then it is 4( sometime it is 6, sometime some crazy values), I was wondering why not my program is printing 100 twice?

After spening some time on it I got the cause .. as "obj" has a local scope( in the routine createTestClassObject ), hence the object dies when program flow returns to "main" and m_TestClassbecome a Dangling Pointer( I hope I am correct :) ).

I was just trying out several options to fix this issue ... and one of them paid off , this is what I did ...
I have just modified the createTestClassObject routine .. and the updated version looks like........
void createTestClassObject()
{
TestClass *obj = new TestClass();
m_TestClass = obj;
m_TestClass ->setAge(100);
printf("\n%d", m_TestClass->getAge());
}

All I have changed is created a pointer of TestClass and it points to new instance of TestClass, and it started working, but all in all I am confused, doesn't the object( new TestClass() )get dies when the routine returns to the main function ? I am in dark, can anybody please throw some light.
Neo.





Wednesday, July 20, 2005

XML Writer and encoding schemes

This all started when my friend Richard asked me to look into some code snippets, all he was trying to do is framing a xml document and flushing it to the console .. and although he has specified utf-8 as encoding scheme( he has used XmlWriterSetting object for this purpose ), but when it comes to console it was like this

so .. it is confusing .. isn't it ? I will request to read his blog as well .. < http://blogs.geekdojo.net/richardhsu/archive/2005/07/16/8675.aspx >
one thing to mention Richard has written codes in .NET Framework 2.0 ... so if you try his code snippet in framwwork 1.1 .. you will get couple of compilation errors.

I did some research on the code and I think I have found the reason of IBM437 issue. Please look at the code folliowing code sinppets ... ( I have used framework 1.1 )

private void btnWriter_Click(object sender, System.EventArgs e)
{
try
{
string fileName = @"C:\test.txt";
System.IO.TextWriter tx = new System.IO.StreamWriter( fileName );
XmlTextWriter writer = new XmlTextWriter( Console.Out );
//XmlTextWriter writer = new XmlTextWriter( tx ); // this will give u utf-8 encoding.

//Console.Out.Encoding = System.Text.Encoding.UTF8; // can't do this..!!!
writer.Formatting = Formatting.Indented;
writer.WriteStartDocument( true );
WriteQuote(writer, "MSFT", 74.125, 5.89, 69020000);
writer.Flush();
writer.Close();
MessageBox.Show( " Done ");
}
catch(Exception ex)
{
MessageBox.Show( ex.Message );
}
}

private void WriteQuote(XmlWriter writer, string symbol,
double price, double change, long volume)
{
writer.WriteStartElement("Stock");
writer.WriteAttributeString("Symbol", symbol);
writer.WriteElementString("Price", XmlConvert.ToString(price));
writer.WriteElementString("Change", XmlConvert.ToString(change));
writer.WriteElementString("Volume", XmlConvert.ToString(volume));
writer.WriteEndElement();
}

My understanding ....
Console.Out gives you an object of type TextWriter( which is essentially point to console .. unless you are doing any console.SetOut- > and pointing the output to any object, other than console ) and if you look at the encoding scheme of this TextWriter object, it is IBM437 .. just use this simple code you can get the encoding scheme of the Console.Out ..

System.Text.Encoding enc = Console.Out.Encoding;
MessageBox.Show( enc.HeaderName);

and unfortunately it is a Readonly property, -:(

Now .. the most important point is Richard have used another object XMLWritersetting .. which is a new addition of .NET framework 2.0( I have played very lil time with 2.0 framework ) ... I am not sure if we set encoding scheme using this object whether it will override the default encoding scheme, if it should .. then it's just another bug in the MS code .. -:).
alternatively
1) we can use a StreamWriter object which also inherits TextWriter object and here the default encoding scheme is utf-8, which solve the purpose.
2) we can use WriteProcessingInstruction method which overrides the default behavior , which Richard does as well.





Tuesday, July 19, 2005

Complicated Heart

Neo's den: July 2005

Love... emotion .. anger ... happiness .. they say it all comes from heart. Sometime I wonder about the mechanism of this machine ..well .. huh .. is it a machine ? I had a big fight with my sys Esha on this. anyway ... so what if it malfunction ? like it will only produce love nothing else ... I think we can avoid all the wars ... and hatred.. and bla bla .. which are the cause of all the problems we have today. Imagine we have got the mechanism to control heart ... and we will pull out the parts from the heart which produce Anger/hatred ..etc etc .. ( I never said it will be easy ).
then hey presto .. all the problem solved .. we don't have to worry about another world war or another 9/11 or 7/7. we will all live in peace for ever.
Lastly I want to add a joke ... why love is easier to promote than war ? hmmm .. condom is cheaper than even a bullet( forget gun ) .. nice one .. huh ?

Saturday, July 09, 2005

sfdsf